1、服務端:數組
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; namespace Server { class Program { static void Main(string[] args) { startServer(); Console.ReadKey(); } static void startServer() { Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 88); serverSocket.Bind(ipEndPoint); serverSocket.Listen(0); serverSocket.BeginAccept(AcceptCallBack, serverSocket); } static messageInfo msgInfo = new messageInfo(); static void AcceptCallBack(IAsyncResult ar) { Socket serverSocket = ar.AsyncState as Socket; Socket clientSocket = serverSocket.EndAccept(ar); clientSocket.Send(Encoding.UTF8.GetBytes("歡迎鏈接,你好客戶端")); clientSocket.BeginReceive(msgInfo.Data, msgInfo.StartIndex, msgInfo.RemainSize, SocketFlags.None, receiveCallBack, clientSocket); serverSocket.BeginAccept(AcceptCallBack, serverSocket); } static byte[] receiveMsg = new byte[1024]; static void receiveCallBack(IAsyncResult ar) { Socket clientSocket = null; try { clientSocket = ar.AsyncState as Socket; int count = clientSocket.EndReceive(ar); if (count == 0) { clientSocket.Close(); return; } msgInfo.AddCount(count); msgInfo.ReadMessage(); clientSocket.BeginReceive(msgInfo.Data, msgInfo.StartIndex, msgInfo.RemainSize, SocketFlags.None, receiveCallBack, clientSocket); } catch (Exception e) { Console.WriteLine(e); if (clientSocket != null) { clientSocket.Close(); return; } } } } }
服務端處理粘包分包:spa
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Server { class messageInfo { //用於存儲接受到的報文 private byte[] data = new byte[1024]; //接收的報文byte的數量 private int startIndex = 0; #region 屬性 //報文 public byte[] Data { get { return data; } } //接收的報文byte的數量 public int StartIndex { get { return startIndex; } } //data數組裏還剩餘的大小 public int RemainSize { get { return data.Length - startIndex; } } #endregion //對報文byte數量的處理 public void AddCount(int count) { startIndex += count; } public void ReadMessage() { while (true) { //若是接收到的數據的個數少於等於4,即少於報頭的大小 if (startIndex <= 4) return; //若是大於報頭的長度,把報頭轉換成數字。ToInt32在處理byte時,從0開始,只處理前四位 int count = BitConverter.ToInt32(data, 0); //若是接收到的數據的個數,減去報頭的大小,大於等於報文的長度,則處理報文。不然不處理 if ((startIndex - 4) >= count) { //從報頭結尾處開始處理,處理count個,count即報文的個數 string s = Encoding.UTF8.GetString(data, 4, count); Console.WriteLine("解析出一條數據 : == :" + s); //處理報文後,則把剩餘的數據向前移動。從count + 4的地方開始向前移動,移動到0處,移動的長度爲接收到的數據減去報文的數量和報頭的數量(即count + 4) Array.Copy(data, count + 4, data, 0, startIndex - count - 4); //移動完成後,處理startIndex即剩餘的接收的數據個數 startIndex -= (count + 4); } else { break; } } } } }
2、客戶端處理代碼:code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; namespace Client { class Program { static void Main(string[] args) { Socket clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress,88); clientSocket.Connect(ipEndPoint); byte[] receiveMsg = new byte[1024]; int count = clientSocket.Receive(receiveMsg); Console.WriteLine(Encoding.UTF8.GetString(receiveMsg,0,count)); while (true) { string sendMsg = Console.ReadLine(); clientSocket.Send(messageInfo.GetBytes(sendMsg)); } Console.ReadKey(); } } }
客戶端處理粘包分包代碼:server
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Client { class messageInfo { /// <summary> /// 把報頭和報文封裝到一塊 /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] GetBytes(string data) { //獲取byte數據 byte[] dateInfo = Encoding.UTF8.GetBytes(data); //獲取報文長度 int length = dateInfo.Length; //把報文長度轉換成byte數組,做爲報頭存在 byte[] lengthByte = BitConverter.GetBytes(length); //把報頭和報文拼接起來,造成一個新的byte數組,返回 byte[] newData = lengthByte.Concat(dateInfo).ToArray(); return newData; } } }