溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#中Socket編程如何實現(xiàn)簡單的局域網(wǎng)聊天器

發(fā)布時間:2021-05-17 13:16:28 來源:億速云 閱讀:224 作者:小新 欄目:編程語言

這篇文章主要介紹C#中Socket編程如何實現(xiàn)簡單的局域網(wǎng)聊天器,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

先上圖。S-Chat是服務(wù)端,C-Chat是客戶端,兩者除了客戶端首次啟動后需要設(shè)置一下連接的IP地址外,無其他區(qū)別。操作與界面都完全相同,對于用戶來說,基本不用在意誰是服務(wù)端誰是客戶端。

C#中Socket編程如何實現(xiàn)簡單的局域網(wǎng)聊天器

C#中Socket編程如何實現(xiàn)簡單的局域網(wǎng)聊天器

編碼

服務(wù)端監(jiān)聽接口

服務(wù)端主要負(fù)責(zé)開啟監(jiān)聽線程,等待客戶端接入

public void StartListen()
{
 // 創(chuàng)建Socket對象 new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
 Socket socket = GetSocket();
 // 將套接字與IPEndPoint綁定
 socket.Bind(this.GetIPEndPoint());
 // 開啟監(jiān)聽 僅支持一個連接
 socket.Listen(1);
 // 開啟線程等待客戶端接入,避免堵塞
 Thread acceptThread = new Thread(new ThreadStart(TryAccept));
 acceptThread.IsBackground = true;
 acceptThread.Start();
}

public void TryAccept()
{
 Socket socket = GetSocket();
 while (true)
 {
  try
  {
   Socket connectedSocket = socket.Accept()
   this.ConnectedSocket = connectedSocket;
   OnConnect(); // 連接成功回調(diào)
   this.StartReceive(); // 開始接收線程
   break;
  }
  catch (Exception e)
  {
  }
 }
}

客戶端連接接口

客戶端主要負(fù)責(zé)開啟連接線程,每隔2秒,自動嘗試連接服務(wù)端

public void StartConnect()
{
 Thread connectThread = new Thread(new ThreadStart(TryConnect));
 connectThread.IsBackground = true;
 connectThread.Start();
}

public void TryConnect()
{
 Socket socket = GetSocket();
 while (true)
 {
  try
  {
   socket.Connect(this.GetIPEndPoint());
   this.ConnectedSocket = socket;
   OnConnect(); // 連接成功回調(diào)
   this.StartReceive();
   break;
  }
  catch (Exception e)
  {
   Thread.Sleep(TryConnectInterval); // 指定間隔后重新嘗試連接
  }
 }
}

文字發(fā)送,文件發(fā)送,接收文字,接收文件等通用接口主要實現(xiàn)在 ChatBase 類中,是服務(wù)端與客戶端的共同父類。

文字發(fā)送接口

發(fā)送數(shù)據(jù)的第一位表示發(fā)送信息的類型,0表示字符串文字,1表示文件

然后獲取待發(fā)送字符串的長度,使用long類型表示,占用8個字節(jié)

共發(fā)送的字節(jié)數(shù)據(jù)可以表示為頭部(類型 + 字符串字節(jié)長度,共9個字節(jié))+ 實際字符串字節(jié)數(shù)據(jù)

public bool Send(string msg)
{
 if (ConnectedSocket != null && ConnectedSocket.Connected)
 {
  byte[] buffer = UTF8.GetBytes(msg); 
  byte[] len = BitConverter.GetBytes((long)buffer.Length); 
  byte[] content = new byte[1 + len.Length + buffer.Length]; 
  content[0] = (byte)ChatType.Str; // 發(fā)送信息類型,字符串
  Array.Copy(len, 0, content, 1, len.Length); // 字符串字節(jié)長度
  Array.Copy(buffer, 0, content, 1 + len.Length, buffer.Length); // 實際字符串字節(jié)數(shù)據(jù)
  try
  {
   ConnectedSocket.Send(content);
   return true;
  }
  catch (Exception e)
  {
  }
 }
 return false;
}

文件發(fā)送接口

與字符串發(fā)送相同的頭部可以表示為(類型 + 文件長度,共9個字節(jié))

還需要再加上待發(fā)送的文件名的長度,與文件名字節(jié)數(shù)據(jù)

共發(fā)送的字節(jié)數(shù)據(jù)可以表示為頭部(類型 + 文件長度,共9個字節(jié))+ 文件名頭部(文件名長度 + 文件名字節(jié)數(shù)據(jù))+ 實際文件數(shù)據(jù)

public bool SendFile(string path)
{
 if (ConnectedSocket != null && ConnectedSocket.Connected)
 {
  try
  {
   FileInfo fi = new FileInfo(path);
   byte[] len = BitConverter.GetBytes(fi.Length); 
   byte[] name = UTF8.GetBytes(fi.Name); 
   byte[] nameLen = BitConverter.GetBytes(name.Length); 
   byte[] head = new byte[1 + len.Length + nameLen.Length + name.Length];
   head[0] = (byte)ChatType.File; // 加上信息發(fā)送類型
   Array.Copy(len, 0, head, 1, len.Length); // 加上文件長度
   Array.Copy(nameLen, 0, head, 1 + len.Length, nameLen.Length); // 加上文件名長度
   Array.Copy(name, 0, head, 1 + len.Length + nameLen.Length, name.Length); // 加上文件名字節(jié)數(shù)據(jù)
   ConnectedSocket.SendFile(
    path,
    head,
    null,
    TransmitFileOptions.UseDefaultWorkerThread
   );
   return true;
  }
  catch(Exception e)
  {
  }
 }
 return false;
}

信息接收接口(文字與文件)

主要是解析接收到的字節(jié)數(shù)據(jù),根據(jù)字符串或文件的類型進行處理

public void Receive()
{
 if (ConnectedSocket != null)
 {
  while (true)
  {
   try
   {
    // 讀取公共頭部
    byte[] head = new byte[9];
    ConnectedSocket.Receive(head, head.Length, SocketFlags.None);
    int len = BitConverter.ToInt32(head, 1);
    if (head[0] == (byte) ChatType.Str)
    {
     // 接收字符串
     byte[] buffer = new byte[len];
     ConnectedSocket.Receive(buffer, len, SocketFlags.None);
     OnReceive(ChatType.Str, UTF8.GetString(buffer));
    }
    else if(head[0] == (byte)ChatType.File)
    {
     // 接收文件
     if (!Directory.Exists(dirName))
     {
      Directory.CreateDirectory(dirName);
     }
     // 讀取文件名信息
     byte[] nameLen = new byte[4];
     ConnectedSocket.Receive(nameLen, nameLen.Length, SocketFlags.None);
     byte[] name = new byte[BitConverter.ToInt32(nameLen, 0)];
     ConnectedSocket.Receive(name, name.Length, SocketFlags.None);
     string fileName = UTF8.GetString(name);
     // 讀取文件內(nèi)容并寫入
     int readByte = 0;
     int count = 0;
     byte[] buffer = new byte[1024 * 8];
     string filePath = Path.Combine(dirName, fileName);
     if (File.Exists(filePath))
     {
      File.Delete(filePath);
     }
     using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
     {
      while (count != len)
      {
       int readLength = buffer.Length;
       if(len - count < readLength)
       {
        readLength = len - count;
       }
       readByte = ConnectedSocket.Receive(buffer, readLength, SocketFlags.None);
       fs.Write(buffer, 0, readByte);
       count += readByte;
      }
     }
     OnReceive(ChatType.File, fileName); 
    }
    else
    {
     // 未知類型
    }
   }
   catch (Exception e)
   {
   }
  }
 }
}

使用

第一次使用,客戶端需要設(shè)置待連接的IP地址。之后再啟動會自動連接

雙擊服務(wù)端exe啟動,點擊 設(shè)置 ,查看IP地址項

C#中Socket編程如何實現(xiàn)簡單的局域網(wǎng)聊天器

雙擊客戶端exe啟動,點擊 設(shè)置 ,在 IP地址 項,輸入服務(wù)端查看到的IP地址

C#中Socket編程如何實現(xiàn)簡單的局域網(wǎng)聊天器 

  • 設(shè)置成功后,等待大約一兩秒,應(yīng)用cion變成綠色,即表示連接成功,可以正常發(fā)送文字和文件了

  • 可以點擊選擇文件(支持選擇多個文件),發(fā)送文件

  • 支持直接拖拽文件到輸入框,發(fā)送文件

  • 支持Ctrl+Enter快捷鍵發(fā)送

  • 接收到的文件自動存放在exe所在目錄的ChatFiles文件夾下

注意事項

客戶端服務(wù)端需要在同一個局域網(wǎng)下才能實現(xiàn)連接
服務(wù)端IP地址是不支持修改的,自動讀取本機的IP地址

C#是什么

C#是一個簡單、通用、面向?qū)ο蟮木幊陶Z言,它由微軟Microsoft開發(fā),繼承了C和C++強大功能,并且去掉了一些它們的復(fù)雜特性,C#綜合了VB簡單的可視化操作和C++的高運行效率,以其強大的操作能力、優(yōu)雅的語法風(fēng)格、創(chuàng)新的語言特性和便捷的面向組件編程從而成為.NET開發(fā)的首選語言,但它不適用于編寫時間急迫或性能非常高的代碼,因為C#缺乏性能極高的應(yīng)用程序所需要的關(guān)鍵功能。

以上是“C#中Socket編程如何實現(xiàn)簡單的局域網(wǎng)聊天器”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI