Socket的三个功能类TCPClient、TCPListener 和 UDPClient (转)

应用程序可以通过 TCPClient、TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务。这些协议类建立在 System.Net.Sockets.Socket 类的基础之上,负责数据传送的细节。(也就是说TCPClient、TCPListener 和 UDPClient 类是用来简化Socket)

TcpClient 和 TcpListener 使用 NetworkStream 类表示网络。使用 GetStream 方法返回网络流,然后调用该流的 Read 和 Write 方法。NetworkStream 不拥有协议类的基础套接字,因此关闭它并不影响套接字。

UdpClient 类使用字节数组保存 UDP 数据文报。使用 Send 方法向网络发送数据,使用 Receive 方法接收传入的数据文报。

1.TcpClient     TcpClient 类提供了一些简单的方法,用于在同步阻止模式下通过网络来连接、发送和接收流数据。为使 TcpClient 连接并交换数据,使用 TCP ProtocolType 创建的 TcpListener 或 Socket 必须侦听是否有传入的连接请求。可以使用下面两种方法之一连接到该侦听器:    (1)创建一个 TcpClient,并调用三个可用的 Connect 方法之一。    (2)使用远程主机的主机名和端口号创建 TcpClient。此构造函数将自动尝试一个连接。     给继承者的说明要发送和接收数据,请使用 GetStream 方法来获取一个 NetworkStream。调用 NetworkStream 的 Write 和 Read 方法与远程主机之间发送和接收数据。使用 Close 方法释放与 TcpClient 关联的所有资源。

  1. 同步通信:
  2. 预定义结构体,同步通信没有多线程异步委托回调,所以无需预定义结构体
  3. 客户端Client
  4. class Program
  5. {
  6. static void Main()
  7. {
  8. try{
  9. int port = ;
  10. string host = "127.0.0.1";
  11. IPAddress ip = IPAddress.Parse(host);
  12. IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
  13. Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
  14. Console.WriteLine("Conneting...");
  15. c.Connect(ipe);//连接到服务器
  16. string sendStr = "hello!This is a socket test";
  17. byte[] bs = Encoding.ASCII.GetBytes(sendStr);
  18. Console.WriteLine("Send Message");
  19. c.Send(bs, bs.Length, );//发送测试信息
  20. string recvStr = "";
  21. byte[] recvBytes = new byte[];
  22. int bytes;
  23. bytes = c.Receive(recvBytes, recvBytes.Length, );//从服务器端接受返回信息
  24. recvStr += Encoding.ASCII.GetString(recvBytes, , bytes);
  25. Console.WriteLine("Client Get Message:{0}", recvStr);//显示服务器返回信息
  26. c.Close();
  27. }
  28. catch (ArgumentNullException e){
  29. Console.WriteLine("ArgumentNullException: {0}", e);
  30. }
  31. catch (SocketException e){
  32. Console.WriteLine("SocketException: {0}", e);
  33. }
  34. Console.WriteLine("Press Enter to Exit");
  35. Console.ReadLine();
  36. }
  37. }
  38.  
  39. 服务器端:
  40.  
  41. class Program
  42. {
  43. static void Main()
  44. {
  45. try{
  46. int port = ;
  47. string host = "127.0.0.1";
  48. IPAddress ip = IPAddress.Parse(host);
  49. IPEndPoint ipe = new IPEndPoint(ip, port);
  50. Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
  51. s.Bind(ipe);//绑定2000端口
  52. s.Listen();//开始监听
  53. Console.WriteLine("Wait for connect");
  54. Socket temp = s.Accept();//为新建连接创建新的Socket。
  55. Console.WriteLine("Get a connect");
  56. string recvStr = "";
  57. byte[] recvBytes = new byte[];
  58. int bytes;
  59. bytes = temp.Receive(recvBytes, recvBytes.Length, );//从客户端接受信息
  60. recvStr += Encoding.ASCII.GetString(recvBytes, , bytes);
  61. Console.WriteLine("Server Get Message:{0}", recvStr);//把客户端传来的信息显示出来
  62. string sendStr = "Ok!Client Send Message Sucessful!";
  63. byte[] bs = Encoding.ASCII.GetBytes(sendStr);
  64. temp.Send(bs, bs.Length, );//返回客户端成功信息
  65. temp.Close();
  66. s.Close();
  67. }
  68. catch (ArgumentNullException e){
  69. Console.WriteLine("ArgumentNullException: {0}", e);}
  70. catch (SocketException e){
  71. Console.WriteLine("SocketException: {0}", e);}
  72. Console.WriteLine("Press Enter to Exit");
  73. Console.ReadLine();
  74. }
  75. }
  76.  
  77. 异步通信:
  78. 客户端Client
  79. 预定义结构体,用于异步委托之间的传递。用户根据自己需要定制即可
  80. public class StateObject
  81. {
  82. // Client socket.
  83. public Socket workSocket = null;
  84. // Size of receive buffer.
  85. public const int BufferSize = ;
  86. // Receive buffer.
  87. public byte[] buffer = new byte[BufferSize];
  88. // Received data string.
  89. public StringBuilder sb = new StringBuilder();
  90. }
  91. 正文:
  92. public class AsynchronousClient
  93. {
  94. // The port number for the remote device.
  95. private const int port = ;
  96. // ManualResetEvent instances signal completion.
  97. private static ManualResetEvent connectDone = new ManualResetEvent(false);
  98. private static ManualResetEvent sendDone = new ManualResetEvent(false);
  99. private static ManualResetEvent receiveDone = new ManualResetEvent(false);
  100. // The response from the remote device.
  101. private static String response = String.Empty;
  102.  
  103. private static void StartClient(){
  104. // Connect to a remote device.
  105. try{
  106. // Establish the remote endpoint for the socket.
  107. // The name of the remote device is "host.contoso.com".
  108. IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
  109. IPAddress ipAddress = ipHostInfo.AddressList[];
  110. IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
  111.  
  112. // Create a TCP/IP socket.
  113. Socket client = new Socket(AddressFamily.InterNetwork,
  114. SocketType.Stream, ProtocolType.Tcp);
  115.  
  116. // Connect to the remote endpoint.
  117. client.BeginConnect(remoteEP,
  118. new AsyncCallback(ConnectCallback), client);
  119. connectDone.WaitOne();
  120.  
  121. // Send test data to the remote device.
  122. Send(client, "This is a test<EOF>");
  123. sendDone.WaitOne();
  124.  
  125. // Receive the response from the remote device.
  126. Receive(client);
  127. receiveDone.WaitOne();
  128.  
  129. // Write the response to the console.
  130. Console.WriteLine("Response received : {0}", response);
  131.  
  132. // Release the socket.
  133. client.Shutdown(SocketShutdown.Both);
  134. client.Close();
  135. }
  136. catch (Exception e){
  137. Console.WriteLine(e.ToString());}
  138. }
  139.  
  140. private static void ConnectCallback(IAsyncResult ar)
  141. {
  142. try{
  143. // Retrieve the socket from the state object.
  144. Socket client = (Socket)ar.AsyncState;
  145.  
  146. // Complete the connection.
  147. client.EndConnect(ar);
  148.  
  149. Console.WriteLine("Socket connected to {0}",
  150. client.RemoteEndPoint.ToString());
  151.  
  152. // Signal that the connection has been made.
  153. connectDone.Set();
  154. }
  155. catch (Exception e){
  156. Console.WriteLine(e.ToString());}
  157. }
  158.  
  159. private static void Receive(Socket client)
  160. {
  161. try{
  162. // Create the state object.
  163. StateObject state = new StateObject();
  164. state.workSocket = client;
  165.  
  166. // Begin receiving the data from the remote device.
  167. client.BeginReceive(state.buffer, , StateObject.BufferSize, ,
  168. new AsyncCallback(ReceiveCallback), state);
  169. }
  170. catch (Exception e){
  171. Console.WriteLine(e.ToString());}
  172. }
  173.  
  174. private static void ReceiveCallback(IAsyncResult ar)
  175. {
  176. try{
  177. // Retrieve the state object and the client socket
  178. // from the asynchronous state object.
  179. StateObject state = (StateObject)ar.AsyncState;
  180. Socket client = state.workSocket;
  181.  
  182. // Read data from the remote device.
  183. int bytesRead = client.EndReceive(ar);
  184.  
  185. if (bytesRead > ){
  186. // There might be more data, so store the data received so far.
  187. state.sb.Append(Encoding.ASCII.GetString(state.buffer, , bytesRead));
  188.  
  189. // Get the rest of the data.
  190. client.BeginReceive(state.buffer, , StateObject.BufferSize, ,
  191. new AsyncCallback(ReceiveCallback), state);
  192. }
  193. else{
  194. // All the data has arrived; put it in response.
  195. if (state.sb.Length > )
  196. {
  197. response = state.sb.ToString();
  198. }
  199. // Signal that all bytes have been received.
  200. receiveDone.Set();
  201. }
  202. }
  203. catch (Exception e){
  204. Console.WriteLine(e.ToString());}
  205. }
  206.  
  207. private static void Send(Socket client, String data)
  208. {
  209. // Convert the string data to byte data using ASCII encoding.
  210. byte[] byteData = Encoding.ASCII.GetBytes(data);
  211.  
  212. // Begin sending the data to the remote device.
  213. client.BeginSend(byteData, , byteData.Length, ,
  214. new AsyncCallback(SendCallback), client);
  215. }
  216.  
  217. private static void SendCallback(IAsyncResult ar)
  218. {
  219. try{
  220. // Retrieve the socket from the state object.
  221. Socket client = (Socket)ar.AsyncState;
  222.  
  223. // Complete sending the data to the remote device.
  224. int bytesSent = client.EndSend(ar);
  225. Console.WriteLine("Sent {0} bytes to server.", bytesSent);
  226.  
  227. // Signal that all bytes have been sent.
  228. sendDone.Set();
  229. }
  230. catch (Exception e){
  231. Console.WriteLine(e.ToString());}
  232. }
  233.  
  234. public static int Main(String[] args)
  235. {
  236. StartClient();
  237. return ;
  238. }
  239. }
  240.  
  241. 服务器端Server
  242. 预定义结构体,用于异步委托之间的传递。同客户端的一致。不再赘述
  243. 正文:
  244.  
  245. // State object for reading client data asynchronously
  246. public class AsynchronousSocketListener
  247. {
  248. // Thread signal.
  249. public static ManualResetEvent allDone = new ManualResetEvent(false);
  250. public AsynchronousSocketListener(){}
  251. public static void StartListening()
  252. {
  253. // Data buffer for incoming data.
  254. byte[] bytes = new Byte[];
  255. // Establish the local endpoint for the socket.
  256. // The DNS name of the computer
  257. // running the listener is "host.contoso.com".
  258.  
  259. //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
  260. IPHostEntry ipHostInfo = Dns.Resolve("127.0.0.1");
  261. IPAddress ipAddress = ipHostInfo.AddressList[];
  262. IPEndPoint localEndPoint = new IPEndPoint(ipAddress, );
  263. // Create a TCP/IP socket.
  264. Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
  265. // Bind the socket to the local endpoint and listen for incoming connections.
  266. try{
  267. listener.Bind(localEndPoint);
  268. listener.Listen();
  269. while (true){
  270. // Set the event to nonsignaled state.
  271. allDone.Reset();
  272. // Start an asynchronous socket to listen for connections.
  273. Console.WriteLine("Waiting for a connection...");
  274. listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
  275. // Wait until a connection is made before continuing.
  276. allDone.WaitOne();
  277. }
  278. }
  279. catch (Exception e){
  280. Console.WriteLine(e.ToString());}
  281. Console.WriteLine("\nPress ENTER to continue...");
  282. Console.Read();
  283. }
  284. public static void AcceptCallback(IAsyncResult ar)
  285. {
  286. // Signal the main thread to continue.
  287. allDone.Set();
  288. // Get the socket that handles the client request.
  289. Socket listener = (Socket)ar.AsyncState;
  290. Socket handler = listener.EndAccept(ar);
  291. // Create the state object.
  292. StateObject state = new StateObject();
  293. state.workSocket = handler;
  294. handler.BeginReceive(state.buffer, , StateObject.BufferSize, ,new AsyncCallback(ReadCallback), state);
  295. }
  296. public static void ReadCallback(IAsyncResult ar)
  297. {
  298. String content = String.Empty;
  299. // Retrieve the state object and the handler socket
  300. // from the asynchronous state object.
  301. StateObject state = (StateObject)ar.AsyncState;
  302. Socket handler = state.workSocket;
  303. // Read data from the client socket.
  304. int bytesRead = handler.EndReceive(ar);
  305. if (bytesRead > )
  306. {
  307. // There might be more data, so store the data received so far.
  308. state.sb.Append(Encoding.ASCII.GetString(state.buffer, , bytesRead));
  309. // Check for end-of-file tag. If it is not there, read
  310. // more data.
  311. content = state.sb.ToString();
  312. if (content.IndexOf("<EOF>") > -){
  313. // All the data has been read from the
  314. // client. Display it on the console.
  315. Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
  316. content.Length, content);
  317. // Echo the data back to the client.
  318. Send(handler, "Server return :" + content);
  319. }
  320. else{
  321. // Not all data received. Get more.
  322. handler.BeginReceive(state.buffer, , StateObject.BufferSize, ,
  323. new AsyncCallback(ReadCallback), state);
  324. }
  325. }
  326. }
  327. private static void Send(Socket handler, String data){
  328. // Convert the string data to byte data using ASCII encoding.
  329. byte[] byteData = Encoding.ASCII.GetBytes(data);
  330. // Begin sending the data to the remote device.
  331. handler.BeginSend(byteData, , byteData.Length, ,
  332. new AsyncCallback(SendCallback), handler);
  333. }
  334. private static void SendCallback(IAsyncResult ar)
  335. {
  336. try{
  337. // Retrieve the socket from the state object.
  338. Socket handler = (Socket)ar.AsyncState;
  339. // Complete sending the data to the remote device.
  340. int bytesSent = handler.EndSend(ar);
  341. Console.WriteLine("Sent {0} bytes to client.", bytesSent);
  342. handler.Shutdown(SocketShutdown.Both);
  343. handler.Close();
  344. }
  345. catch (Exception e){
  346. Console.WriteLine(e.ToString());
  347. }
  348. }
  349. public static int Main(String[] args)
  350. {
  351. StartListening();
  352. return ;
  353. }
  354. }

【socket】Socket的三个功能类TCPClient、TCPListener 和 UDPClient的更多相关文章

  1. Socket的三个功能类TCPClient、TCPListener 和 UDPClient (转)

    应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务.这些协议类建立在 System.Net.So ...

  2. C#编程 socket编程之TcpClient,TcpListener,UdpClient

    应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务.这些协议类建立在 System.Net.So ...

  3. Socket异步通信学习三

    接下来是客户端部分,采用同步接收模式,在SocketClient项目中新建了一个SynServer类,用于存放socket服务器代码,和AsynServer类似,主要有4个方法: 有一个全局socke ...

  4. socket通信原理三次握手和四次握手详解

    对TCP/IP.UDP.Socket编程这些词你不会很陌生吧?随着网络技术的发展,这些词充斥着我们的耳朵.那么我想问: 1.         什么是TCP/IP.UDP?2.         Sock ...

  5. Python 基础之socket编程(三)

    python 基础之socket编程(三) 前面实现的基于socket通信只能实现什么呢?在tcp协议的通信中就是一个用户说一句,服务端给你回一句,你再给服务端说一句,服务端再给你回一句,就这样一直友 ...

  6. Socket 学习(三).4 UDP 穿透 客户端与客户端连接

    效果图: 使用方法:  先 修改WinClient\bin\Debug  下面的 ip.ini,写上 服务器 IP地址. 客户端 与 客户端 通讯 之前 ,点击发送打洞消息 按钮,然后过一会再发送消息 ...

  7. 运用socket实现简单的ssh功能

    在python socket知识点中已经对socket进行了初步的了解,那现在就使用这些知识来实现一个简单的ssh(Secure Shell)功能. 首先同样是建立两个端(服务器端和客户端) 需求是: ...

  8. Socket网络编程(TCP/IP/端口/类)和实例

    Socket网络编程(TCP/IP/端口/类)和实例 原文:C# Socket网络编程精华篇 转自:微冷的雨 我们在讲解Socket编程前,先看几个和Socket编程紧密相关的概念: TCP/IP层次 ...

  9. C#高性能大容量SOCKET并发(三):接收、发送

    原文:C#高性能大容量SOCKET并发(三):接收.发送 异步数据接收有可能收到的数据不是一个完整包,或者接收到的数据超过一个包的大小,因此我们需要把接收的数据进行缓存.异步发送我们也需要把每个发送的 ...

随机推荐

  1. linux压缩解压缩

    一.tar • -c:创建新文档• -x:解压缩归档文件• -f 文件名:使用归档文件• -j:使用bzip2解压缩• -z:使用gzip解压缩• -v:详细输出模式 1.压缩命令: 命令格式:tar ...

  2. 会话跟踪技术——Session

    一.什么是Session Session从用户访问页面开始,到断开与网站连接为止,形成一个会话的生命周期.在会话期间,分配客户唯一的一个SessionID,用来标识当前用户,与其他用户进行区分. Se ...

  3. EasyUI 使用注意点

    前段时间做一个系统的服务端管理系统,使用了一下EasyUI.以下是我在使用中觉得需要注意的地方或者一些EasyUI中一些特别点的用法. 总结如下,与大家分享下,希望对初学者能有些作用. EasyUI ...

  4. Mac环境下svn的使用(转载)

    在Windows环境中,我们一般使用TortoiseSVN来搭建svn环境.在Mac环境下,由于Mac自带了svn的服务器端和客户端功能,所以我们可以在不装任何第三方软件的前提下使用svn功能,不过还 ...

  5. MyBatis(3.2.3) - Configuring MyBatis using XML, Properties

    The properties configuration element can be used to externalize the configuration values into a prop ...

  6. 【转载】Apache Kafka:下一代分布式消息系统

    http://www.infoq.com/cn/articles/kafka-analysis-part-1 Kafka是由LinkedIn开发的一个分布式的消息系统,使用Scala编写,它以可水平扩 ...

  7. CF下的BackgroudWorker组件优化.

    .net compact framwork(2.0/3.5)下没有Backgroundworder组件,在网上找了一个类 经过使用发现了一些问题,主要有一个问题:在一个Dowork事件中对Report ...

  8. Unity 5.4大赞:HTC Vive经典The lab渲染器开源

    HTC Vive提供了一个不错的免费VR demo,最近1周仔细体验了一番. 仔细看了其安装文件,竟然是Unity 5.4beta版本(通过查log,知道Valve公司用的是最新的5.4.0b11版本 ...

  9. ios 一个app启动另一个app

    问题描述:需要从一个ios应用程序中,能启动另一个ios应用程序. 开发环境:xcode7.3.1 关键词:白名单(LSApplicationQueriesSchemes).注册自己的URL Demo ...

  10. DOM_节点层次_Document类型

    一.Document类型 nodeType: 9; nodeName: "#document"; nodeValue: null; parentValue: null; owner ...