Socket  tcpServer =  new  Socket ( AddressFamily. InterNetwork,  SocketType. Stream,  ProtocolType. Tcp) ; 
IPAddress  ipAddress =  new  IPAddress ( new  byte [ ] {  192 ,  168 ,  1 ,  5  } ) ; 
IPEndPoint  ipEndPoint =  new  IPEndPoint ( ipAddress,  7788 ) ; 
tcpServer. Bind ( ipEndPoint) ;  
tcpServer. Listen ( 100 ) ;  
Console. WriteLine ( "开始接客了..." ) ; 
Socket  client =  tcpServer. Accept ( ) ; 
Console. WriteLine ( "一个客户端连接过来了!" ) ; 
byte [ ] =  new  byte [ 1024 ] ; 
int =  client. Receive ( data) ; 
string =  Encoding. UTF8. GetString ( data,  0 ,  length) ; 
Console. WriteLine ( "接收到了客户端的消息:"  +  msg) ; 
client. Send ( Encoding. UTF8. GetBytes ( "来了,随便坐" ) ) ; client. Close ( ) ; 
tcpServer. Close ( ) ; 
Socket  tcpClient =  new  Socket ( AddressFamily. InterNetwork,  SocketType. Stream,  ProtocolType. Tcp) ; 
IPAddress  ipAddress =  new  IPAddress ( new  byte [ ] {  192 ,  168 ,  1 ,  5  } ) ; 
IPEndPoint  ipEndPoint =  new  IPEndPoint ( ipAddress,  7788 ) ; 
tcpClient. Connect ( ipEndPoint) ; 
Console. WriteLine ( "连接上服务器端了!" ) ; 
string =  "我上线了" ; 
tcpClient. Send ( Encoding. UTF8. GetBytes ( msg) ) ; 
byte [ ] =  new  byte [ 1024 ] ; 
int =  tcpClient. Receive ( data) ; 
Console. WriteLine ( "收到服务器端的消息:"  +  Encoding. UTF8. GetString ( data,  0 ,  length) ) ; tcpClient. Close ( ) ; 
基于连接(TCP)和无连接(UDP) 对系统资源的要求(TCP 较多,UDP 少) UDP 程序结构较简单 流模式(TCP)与 数据报模式(UDP) TCP 保证数据的正确性,UDP 可能丢包 TCP 保证数据顺序,UDP 不保证 Socket  udpServer =  new  Socket ( AddressFamily. InterNetwork,  SocketType. Dgram,  ProtocolType. Udp) ; 
IPAddress  ipAddress =  new  IPAddress ( new  byte [ ] {  192 ,  168 ,  1 ,  5  } ) ; 
IPEndPoint  ipEndPoint =  new  IPEndPoint ( ipAddress,  7788 ) ; 
udpServer. Bind ( ipEndPoint) ; IPEndPoint  ipEndPoint2 =  new  IPEndPoint ( IPAddress. Any,  0 ) ; 
EndPoint  ep =  ( EndPoint) ipEndPoint2; 
byte [ ] =  new  byte [ 1024 ] ; 
int =  udpServer. ReceiveFrom ( data,  ref  ep) ;  
Console. WriteLine ( "接收到数据:"  +  Encoding. UTF8. GetString ( data,  0 ,  length) ) ; udpServer. Close ( ) ; 
Socket  udpClient =  new  Socket ( AddressFamily. InterNetwork,  SocketType. Dgram,  ProtocolType. Udp) ; 
IPAddress  ipAddress =  new  IPAddress ( new  byte [ ] {  192 ,  168 ,  1 ,  5  } ) ; 
IPEndPoint  ipEndPoint =  new  IPEndPoint ( ipAddress,  7788 ) ; 
byte [ ] =  Encoding. UTF8. GetBytes ( "您好,客户端上线了!" ) ; 
udpClient. SendTo ( data,  ipEndPoint) ;  udpClient. Close ( ) ;