先看看测试结果:

服务端:

服务器端控制台:

可以发现我服务端连了2个客户端,第一个为局域网的一台机器,另一个为服务器的主机


ip为192.168.1.105 ,端口为42794的客户端:

ip为192.168.1.104,端口为30547的客户端:


需要发送聊天信息 : 使用“chat:”作为前缀。


值得注意的是 : 本文只探讨异步Socket的封装 , 包括包头和包 。对与体验效果不好,不是此次讨论的范围,Sorry。


一,核心 :

①:关于消息的构建类库:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceSocketTool{publicsealedclassSocketMsgTool{///<summary>///构造一个发送包///</summary>///<paramname="mainCode">主码</param>///<paramname="subCode">分码</param>///<paramname="type">类型码</param>///<paramname="Body">包体</param>///<returns></returns>publicstaticbyte[]Creat_Msg(ushortmainCode,ushortsubCode,ushorttype,byte[]Body){List<byte>cur=newList<byte>(Body);cur.InsertRange(0,BitConverter.GetBytes(mainCode));cur.InsertRange(2,BitConverter.GetBytes(subCode));cur.InsertRange(4,BitConverter.GetBytes(type));ushortbody_len=Convert.ToUInt16(Body.Length);cur.InsertRange(6,BitConverter.GetBytes(body_len));returncur.ToArray<byte>();}///<summary>///获取主码///</summary>///<paramname="msg"></param>///<returns></returns>publicstaticushortGet_MainCode(byte[]msg){returnBitConverter.ToUInt16(msg,0);}///<summary>///获取分码///</summary>///<paramname="msg"></param>///<returns></returns>publicstaticushortGet_SubCode(byte[]msg){returnBitConverter.ToUInt16(msg,2);}///<summary>///获取类型码///</summary>///<paramname="msg"></param>///<returns></returns>publicstaticushortGet_Type(byte[]msg){returnBitConverter.ToUInt16(msg,4);}///<summary>///获取包体///</summary>///<paramname="msg"></param>///<returns></returns>publicstaticbyte[]Get_Body(byte[]msg){byte[]body=newbyte[BitConverter.ToUInt16(msg,6)];Array.Copy(msg,8,body,0,body.Length);returnbody;}}}

②关于字节数组方法的扩展:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceAsync_Svr_Socket_Lib.com{///<summary>///字节数组(byte[])的方法扩展///</summary>internalstaticclassByteArr_Fun_Extends{///<summary>///追加数据到Buffer///</summary>///<paramname="buffer"></param>///<paramname="buffer_off_index">数据的偏移下标</param>///<paramname="add">增加的byte[]</param>///<returns>需要增加的size量</returns>publicstaticintPush_Data(thisbyte[]buffer,refintbuffer_off_index,byte[]add){intcur_con_count=buffer.Length-(buffer_off_index+1);if(add.Length>cur_con_count){//需要扩大buffer的sizeintoff=add.Length-cur_con_count;Array.Resize<byte>(refbuffer,buffer.Length+off);//扩充buffer的sizeadd.CopyTo(buffer,buffer_off_index+1);buffer_off_index+=add.Length;//更新偏移returnoff;}else{//不需要扩大buffer的sizeadd.CopyTo(buffer,buffer_off_index+1);buffer_off_index+=add.Length;//更新偏移return0;}}///<summary>///压人新的数据(一般为包头)-构造新的发送包///</summary>///<paramname="buffer_send">需要发送的包体</param>///<paramname="unshift">压入增加的byte[]</param>///<returns>需要增加的size量</returns>publicstaticvoidUnshift_Data(thisbyte[]buffer_send,byte[]unshift){byte[]effective=buffer_send.Skip<byte>(0).Take<byte>(buffer_send.Length).ToArray<byte>();List<byte>list=newList<byte>(effective);list.InsertRange(0,unshift);//头部插入buffer_send=list.ToArray();//重新指定数据}///<summary>///获取当前数据(取出一个完整的包)///</summary>///<paramname="buffer"></param>///<paramname="buffer_off_index">数据的偏移下标</param>///<paramname="cur_len">整个包的长度</param>///<returns>当前的包</returns>publicstaticbyte[]Shift_Data(thisbyte[]buffer,refintbuffer_off_index,intcur_len){byte[]next_buffer=null;if(cur_len<buffer_off_index+1)next_buffer=buffer.Skip<byte>(cur_len-1).Take<byte>(buffer_off_index+1-cur_len).ToArray<byte>();//下一个包(存在粘包)byte[]cur_buffer=buffer.Skip<byte>(0).Take<byte>(cur_len).ToArray<byte>();//当前的包(完整)if(next_buffer==null)buffer_off_index=-1;else{Array.Resize<byte>(refbuffer,next_buffer.Length);next_buffer.CopyTo(buffer,0);//注入新的包buffer_off_index=next_buffer.Length-1;}returncur_buffer;}}}

③关于服务端Socket类库:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Threading;usingAsync_Svr_Socket_Lib.com;usingSystem.ComponentModel;namespaceAsync_Svr_Socket_Lib{///<summary>///服务器Socket封装///</summary>publicsealedclassSvr_Socket{privateSocket_listener=null;//服务器SocketprivatereadonlyIPEndPoint_ip_point=null;privateAction<Socket_CallBack_Type,Object,Socket>_callback=null;//回调函数privatereadonlyint_connect_count=0;privatereadonlyint_state_object_bufferlen=0;privateManualResetEventallDone=null;//信号量privateTimer_heart_beat_timer=null;//心跳包及时机制///<summary>///构造函数///</summary>///<paramname="ip_point">服务端ip+port</param>///<paramname="callback">回调函数</param>///<paramname="connect_count">可连接的服务端个数</param>///<paramname="state_object_bufferlen">clientbuffer长度</param>publicSvr_Socket(IPEndPointip_point,Action<Socket_CallBack_Type,Object,Socket>callback,intconnect_count=100,intstate_object_bufferlen=512){this._ip_point=ip_point;this._callback=callback;this._connect_count=connect_count;this._state_object_bufferlen=state_object_bufferlen;}///<summary>///请求连接Socket服务器///</summary>publicvoidAccept(){this._listener=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//构建Tcp通讯allDone=newManualResetEvent(false);try{this._listener.Bind(this._ip_point);this._listener.Listen(this._connect_count);while(true)//持续的监听连接{allDone.Reset();//置为无信号状态this._listener.BeginAccept(newAsyncCallback(this.Async_Accept_Callback),this._listener);allDone.WaitOne();//当前线程等待}}catch(Exceptione){Console.WriteLine("SocketError!->{0}",e.Message);}}//连接异步回调处理privatevoidAsync_Accept_Callback(IAsyncResultar){allDone.Set();//置为有信号状态Socketlistener=(Socket)ar.AsyncState;try{Socketclient=listener.EndAccept(ar);State_Objectstate=newState_Object(this._state_object_bufferlen);state.Client_Socket=client;this._callback(Socket_CallBack_Type.connect_succ,true,client);//连接成功this.receive(state);}catch(Exceptione){this._callback(Socket_CallBack_Type.connect_fail,e,null);}}//接收字节privatevoidreceive(State_Objectstate){state.Client_Socket.BeginReceive(state.Buffer,state.Buffer_Off_Index+1,state.Buffer.Length-(state.Buffer_Off_Index+1),0,newAsyncCallback(this.Async_Receive_Callback),state);}//接收异步回调处理privatevoidAsync_Receive_Callback(IAsyncResultar){State_Objectstate=(State_Object)ar.AsyncState;try{intbyte_read_count=state.Client_Socket.EndReceive(ar);//接收的字节数if(byte_read_count>0){state.Buffer_Off_Index+=byte_read_count;this.Receive_Handler(state);}else{//玩家主动关闭了连接this._callback(Socket_CallBack_Type.client_active_off,null,state.Client_Socket);}}catch(Exceptione){//玩家被迫断开(客户端没发送断开指令)this._callback(Socket_CallBack_Type.client_passive_off,e,state.Client_Socket);}}///<summary>///处理了粘包及断包///</summary>///<paramname="state"></param>privatevoidReceive_Handler(State_Objectstate){byte[]client_buffer=state.Buffer;if(state.Buffer_Off_Index+1>=8)//如果包头取到{ushortbody_len=BitConverter.ToUInt16(state.Buffer,6);ushortpacket_all_len=Convert.ToUInt16(body_len+8);if(packet_all_len<=state.Buffer_Off_Index+1){intbuffer_off_index=state.Buffer_Off_Index;byte[]cur_packet=state.Buffer.Shift_Data(refbuffer_off_index,packet_all_len);//取出当前的包(一整个包)state.Buffer_Off_Index=buffer_off_index;//重新赋值this._callback(Socket_CallBack_Type.receive,cur_packet,state.Client_Socket);//回调接收到的包if(state.Buffer_Off_Index==-1){Array.Resize<byte>(refclient_buffer,this._state_object_bufferlen);//再次初始化bufferthis.receive(state);}else{this.Receive_Handler(state);}}elseif(packet_all_len>state.Buffer.Length)//当包长大于buffer时{Array.Resize<byte>(refclient_buffer,state.Buffer.Length+this._state_object_bufferlen);this.receive(state);}else{this.receive(state);}}else{this.receive(state);}}///<summary>///发送信息///</summary>///<paramname="socket"></param>///<paramname="msg">要发送的信息</param>publicvoidSend(Socketsocket,byte[]msg){if(socket!=null&&socket.Connected){socket.BeginSend(msg,0,msg.Length,0,newAsyncCallback(this.Async_Send_Callback),socket);}}//发送信息返回privatevoidAsync_Send_Callback(IAsyncResultar){Socketsocket=(Socket)ar.AsyncState;intbyte_send_count=socket.EndSend(ar);this._callback(Socket_CallBack_Type.send,byte_send_count,socket);}}///<summary>///Socket回调类型///</summary>publicenumSocket_CallBack_Type:uint{[Description("连接成功")]connect_succ=0,[Description("连接失败")]connect_fail=1,[Description("接收返回")]receive=2,[Description("发送返回")]send=3,[Description("客户端被迫断开")]client_passive_off=4,[Description("客户端主动断开")]client_active_off=5}}


④关于客户端Socket类库:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Net.Sockets;usingSystem.Net;usingAsync_Cli_Socket_Lib.com;usingSystem.ComponentModel;namespaceAsync_Cli_Socket_Lib{///<summary>///客户端socket///</summary>publicsealedclassCli_Socket{privateSocket_client=null;privateIPEndPoint_ip_point=null;privateAction<Socket_CallBack_Type,Object>_callback=null;privatereadonlyint_state_object_bufferlen=0;privateState_Object_state=null;///<summary>//////</summary>///<paramname="ip_point">服务端ip+port</param>///<paramname="callback">回调函数</param>///<paramname="state_object_bufferlen">buffer默认size</param>publicCli_Socket(IPEndPointip_point,Action<Socket_CallBack_Type,Object>callback,intstate_object_bufferlen=512){this._ip_point=ip_point;this._callback=callback;this._state_object_bufferlen=state_object_bufferlen;this._state=newState_Object(state_object_bufferlen);}///<summary>///获取Socket///</summary>publicSocketClient{get{returnthis._client;}}publicvoidConnect(){if(_client==null)_client=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);_client.BeginConnect(this._ip_point,newAsyncCallback(this.Async_Connect_Callback),_client);}privatevoidAsync_Connect_Callback(IAsyncResultar){Socketclient=(Socket)ar.AsyncState;try{client.EndConnect(ar);this._callback(Socket_CallBack_Type.connect_succ,true);this.receive();//开始接收数据}catch(Exceptione){this._callback(Socket_CallBack_Type.connect_fail,e);}}//开始接收数据privatevoidreceive(){this._client.BeginReceive(this._state.Buffer,this._state.Buffer_Off_Index+1,this._state.Buffer.Length-(this._state.Buffer_Off_Index+1),0,newAsyncCallback(this.Async_Receive_Callback),this._state);}//接收数据返回privatevoidAsync_Receive_Callback(IAsyncResultar){State_Objectstate=(State_Object)ar.AsyncState;try{intbyte_read_count=this._client.EndReceive(ar);//接收的字节数if(byte_read_count>0){state.Buffer_Off_Index+=byte_read_count;//增加的数据量this.Receive_Handler(state);}else{this._callback(Socket_CallBack_Type.server_active_off,this._client);}}catch(Exceptione){this._callback(Socket_CallBack_Type.server_passive_off,e);}}privatevoidReceive_Handler(State_Objectstate){byte[]client_buffer=state.Buffer;if(state.Buffer_Off_Index+1>=8)//包头的信心已经收到{ushortbody_len=BitConverter.ToUInt16(state.Buffer,6);ushortpacket_all_len=Convert.ToUInt16(body_len+8);if(packet_all_len<=state.Buffer_Off_Index+1){intbuffer_off_index=state.Buffer_Off_Index;byte[]cur_packet=state.Buffer.Shift_Data(refbuffer_off_index,packet_all_len);//取出当前的包(一整个包)state.Buffer_Off_Index=buffer_off_index;//重新赋值this._callback(Socket_CallBack_Type.receive,cur_packet);//回调接收到的包------------------if(state.Buffer_Off_Index==-1){Array.Resize<byte>(refclient_buffer,this._state_object_bufferlen);//再次初始化bufferthis.receive();}else{this.Receive_Handler(state);}}elseif(packet_all_len>state.Buffer.Length){Array.Resize<byte>(refclient_buffer,state.Buffer.Length+this._state_object_bufferlen);this.receive();}else{this.receive();}}else{this.receive();}}///<summary>///发送Socket请求///</summary>///<paramname="msg">请求信息</param>publicvoidSend(byte[]msg){_client.BeginSend(msg,0,msg.Length,0,newAsyncCallback(this.Async_Send_Callback),this._state);}privatevoidAsync_Send_Callback(IAsyncResultar){State_Objectstate=(State_Object)ar.AsyncState;intbyte_send_count=this._client.EndSend(ar);//发送了多少字节this._callback(Socket_CallBack_Type.send,byte_send_count);}}///<summary>///Socket回调类型///</summary>publicenumSocket_CallBack_Type:uint{[Description("连接成功")]connect_succ=0,[Description("连接失败")]connect_fail=1,[Description("接收返回")]receive=2,[Description("发送返回")]send=3,[Description("服务端被迫断开")]server_passive_off=4,[Description("服务端主动断开")]server_active_off=5}}

⑤:服务端 state_object

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Net.Sockets;namespaceAsync_Svr_Socket_Lib.com{///<summary>///Socket数据///</summary>internalsealedclassState_Object{///<summary>///ClientSocket///</summary>publicSocketClient_Socket{set;get;}privatebyte[]_buffer=null;privateint_buffer_off_index=-1;///<summary>///构造函数///</summary>///<paramname="buffer_size">缓存初始的字节数</param>publicState_Object(intbuffer_size=512){this._buffer=newbyte[buffer_size];this.Buffer_Off_Index=-1;}///<summary>///字节数组///</summary>publicbyte[]Buffer{get{returnthis._buffer;}}///<summary>///缓存已经存储的下标(显然从0开始,-1表示没有数据)///</summary>publicintBuffer_Off_Index{set{this._buffer_off_index=value;}get{returnthis._buffer_off_index;}}}}

⑥:客户端state_object

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceAsync_Cli_Socket_Lib.com{///<summary>///Socket数据///</summary>internalsealedclassState_Object{privatebyte[]_buffer=null;privateint_buffer_off_index=-1;///<summary>///构造函数///</summary>///<paramname="buffer_size">缓存初始的字节数</param>publicState_Object(intbuffer_size=512){this._buffer=newbyte[buffer_size];this.Buffer_Off_Index=-1;}///<summary>///字节数组///</summary>publicbyte[]Buffer{get{returnthis._buffer;}}///<summary>///缓存已经存储的下标(显然从0开始,-1表示没有数据)///</summary>publicintBuffer_Off_Index{set{this._buffer_off_index=value;}get{returnthis._buffer_off_index;}}}}


二,测试(使用控制台)

①:服务端

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingAsync_Svr_Socket_Lib;usingSystem.Net;usingSystem.Net.Sockets;usingSocketTool;usingSystem.Diagnostics;usingSystem.Threading;namespaceServer_Socket_Test{classProgram{privateDictionary<string,Socket>_client_list=null;//因为测试的环境原因,使用key:姓名,在真实的开发中应该使用用户的ID号privateSvr_Socket_socket=null;//本人封装的服务端SocketstaticvoidMain(string[]args){Console.BackgroundColor=ConsoleColor.Black;Console.ForegroundColor=ConsoleColor.Green;Thread.CurrentThread.IsBackground=true;//退出后自动杀死进程IPEndPointipe=newIPEndPoint(IPAddress.Parse("192.168.1.104"),6065);Programpro=newProgram();pro._socket=newSvr_Socket(ipe,pro.CallBack);Console.WriteLine("等待请求连接.......");pro._socket.Accept();Console.Read();}privatevoidCallBack(Socket_CallBack_Typetype,objectmsg,Socketclient){stringkey=String.Empty;switch(type){caseSocket_CallBack_Type.connect_succ:this.connect(msg,client);break;caseSocket_CallBack_Type.connect_fail:Console.WriteLine("连接失败:{0}",((Exception)msg).Message);break;caseSocket_CallBack_Type.receive:this.receive(msg,client);break;caseSocket_CallBack_Type.send://Console.WriteLine("发送的字节数:{0}",Convert.ToInt32(msg));break;caseSocket_CallBack_Type.client_active_off://主动下线#ifDEBUGConsole.WriteLine("{0}下线了!!",client.RemoteEndPoint);#endifthis.RemoveClient(client);break;caseSocket_CallBack_Type.client_passive_off://被迫下线#ifDEBUGConsole.WriteLine("{0}下线了!!",client.RemoteEndPoint);#endifthis.RemoveClient(client);break;}}///<summary>///玩家下线///</summary>///<paramname="client"></param>privatevoidRemoveClient(Socketclient){if(this._client_list==null)return;stringremove_name=string.Empty;foreach(KeyValuePair<string,Socket>kvinthis._client_list){if(kv.Value==client){remove_name=kv.Key;break;}}this._client_list.Remove(remove_name);if(client!=null&&client.Connected){client.Shutdown(SocketShutdown.Both);client.Close();}if(this._client_list.Count>0){stringremove_msg="{0},下线了!!!";byte[]msg=Encoding.UTF8.GetBytes(string.Format(remove_msg,remove_name));msg=SocketMsgTool.Creat_Msg(1,1,3,msg);foreach(KeyValuePair<string,Socket>kvinthis._client_list){kv.Value.Send(msg);}}}///<summary>///玩家上线///</summary>///<paramname="body"></param>///<paramname="client"></param>privatevoidAddClient(byte[]body,Socketclient){stringstr=Encoding.UTF8.GetString(body);stringname=str.Split(newchar[]{','})[0];Console.WriteLine("{0}>{1}",client.RemoteEndPoint,str);//开始启动服务端的心跳包if(this._client_list==null)this._client_list=newDictionary<string,Socket>();if(!this._client_list.ContainsKey(name))this._client_list.Add(name,client);stringadd_msg="{0},上线了!!!";byte[]msg=Encoding.UTF8.GetBytes(string.Format(add_msg,name));msg=SocketMsgTool.Creat_Msg(1,1,4,msg);foreach(KeyValuePair<string,Socket>kvinthis._client_list){kv.Value.Send(msg);}}privatevoidconnect(objectmsg,Socketclient){Console.WriteLine("连接成功clientip:{0}",client.RemoteEndPoint);byte[]welcome=Encoding.UTF8.GetBytes(String.Format("欢迎:{0},尊姓大名?",client.RemoteEndPoint));welcome=SocketMsgTool.Creat_Msg(1,1,1,welcome);client.Send(welcome);}privatevoidreceive(objectmsg,Socketclient){byte[]data=(byte[])msg;ushortmainCode=SocketMsgTool.Get_MainCode(data);ushortsubCode=SocketMsgTool.Get_SubCode(data);ushorttype=SocketMsgTool.Get_Type(data);byte[]body=SocketMsgTool.Get_Body(data);switch(mainCode){case1:switch(subCode){case0://break;case1:switch(type){case2:this.AddClient(body,client);break;}break;}break;case2:switch(subCode){case1:switch(type){case1://聊天信息this.Chat(body,client);break;}break;}break;}}///<summary>///聊天处理///</summary>///<paramname="body"></param>///<paramname="client"></param>privatevoidChat(byte[]body,Socketclient){stringmsg=Encoding.UTF8.GetString(body);byte[]all_mag=SocketMsgTool.Creat_Msg(2,1,1,body);foreach(KeyValuePair<string,Socket>kvinthis._client_list){if(kv.Value!=client){kv.Value.Send(all_mag);//发送聊天信息}}Console.WriteLine(msg);}}}


②,客户端

usingSystem;usingSystem.Text;usingSystem.Net;usingAsync_Cli_Socket_Lib;usingSocketTool;usingSystem.Net.Sockets;usingSystem.Threading;namespaceClient_Socket_Test{classProgram{privateCli_Socket_socket=null;privatereadonlystring_name=string.Empty;publicProgram(stringname){this._name=name;}staticvoidMain(string[]args){Console.BackgroundColor=ConsoleColor.Black;Console.ForegroundColor=ConsoleColor.Green;Thread.CurrentThread.IsBackground=true;//退出后自动杀死进程Console.Write("请输入用户名:");stringname=Console.ReadLine();IPEndPointipe=newIPEndPoint(IPAddress.Parse("192.168.1.104"),6065);Programpro=newProgram(name);pro._socket=newCli_Socket(ipe,pro.CallBack);Console.WriteLine("请求连接Socket服务器");pro._socket.Connect();stringcode=Console.ReadLine();while(true){if(code.Trim().ToLower()=="off"){pro._socket.Client.Shutdown(SocketShutdown.Both);pro._socket.Client.Close();break;}else{//聊天信息if(code.Trim()!=string.Empty&&code.Trim().Substring(0,5)=="chat:"){pro.Chat(code.Trim().Substring(5));//发送聊天信息}code=Console.ReadLine();}}}///<summary>///发送聊天信息///</summary>///<paramname="msg"></param>privatevoidChat(stringchats){stringmsg=string.Format("{0}说:{1}",_name,chats);byte[]by=SocketMsgTool.Creat_Msg(2,1,1,Encoding.UTF8.GetBytes(msg));this._socket.Send(by);}privatevoidCallBack(Socket_CallBack_Typetype,Objectmsg){switch(type){caseSocket_CallBack_Type.connect_succ:this.connect(msg);break;caseSocket_CallBack_Type.connect_fail:Console.WriteLine("连接失败:{0}",((Exception)msg).Message);break;caseSocket_CallBack_Type.receive:this.receive(msg);break;caseSocket_CallBack_Type.send:Console.WriteLine("发送的字节数:{0}",Convert.ToInt32(msg));break;caseSocket_CallBack_Type.server_active_off:#ifDEBUGConsole.WriteLine("主动:服务器断开连接:{0}",(msgasException).Message);#endifif(_socket.Client!=null&&_socket.Client.Connected){_socket.Client.Shutdown(SocketShutdown.Both);_socket.Client.Close();}break;caseSocket_CallBack_Type.server_passive_off:#ifDEBUGConsole.WriteLine("被迫:服务器断开连接:{0}",(msgasException).Message);#endifif(_socket.Client!=null&&_socket.Client.Connected){_socket.Client.Shutdown(SocketShutdown.Both);_socket.Client.Close();}break;}}privatevoidconnect(objectmsg){Console.WriteLine("已经成功连接到了Socket服务器了");}privatevoidreceive(objectmsg){byte[]data=(byte[])msg;ushortmainCode=SocketMsgTool.Get_MainCode(data);ushortsubCode=SocketMsgTool.Get_SubCode(data);ushorttype=SocketMsgTool.Get_Type(data);byte[]body=SocketMsgTool.Get_Body(data);switch(mainCode){case1:switch(subCode){case1:switch(type){case0:break;case1://Console.WriteLine(Encoding.UTF8.GetString(body));byte[]hello=Encoding.UTF8.GetBytes(string.Format("{0},请多指教",this._name));Console.WriteLine("{0},请多指教",this._name);hello=SocketMsgTool.Creat_Msg(1,1,2,hello);this._socket.Send(hello);break;case3://有玩家下线stringremove_news=string.Format("【{0}】:{1}","Server",Encoding.UTF8.GetString(body));Console.WriteLine(remove_news);break;case4://有玩家上线stringadd_msg=Encoding.UTF8.GetString(body);stringadd_name=add_msg.Split(newchar[]{','})[0];if(add_name!=_name){add_msg=string.Format("【{0}】:{1}","Server",add_msg);Console.WriteLine(add_msg);}break;}break;}break;case2:switch(subCode){case1:switch(type){case1://聊天信息//Console.Clear();stringchat=Encoding.UTF8.GetString(body);Console.WriteLine(chat);break;}break;}break;}}}}

值得注意的是 : 此封装不仅可以用于聊天,body也可以进行加密,用于游戏Socket通讯。

附件:http://down.51cto.com/data/2366908