Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 313|回复: 0

[默认分类] 基于C#的socket编程的TCP异步实现

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-7-12 16:18:31 | 显示全部楼层 |阅读模式
    一、摘要
      本篇博文阐述基于TCP通信协议的异步实现。

    二、实验平台
      Visual Studio 2010

    三、异步通信实现原理及常用方法
    3.1 建立连接 
      在同步模式中,在服务器上使用Accept方法接入连接请求,而在客户端则使用Connect方法来连接服务器。相对地,在异步模式下,服务器可以使用BeginAccept方法和EndAccept方法来完成连接到客户端的任务,在客户端则通过BeginConnect方法和EndConnect方法来实现与服务器的连接。
      BeginAccept在异步方式下传入的连接尝试,它允许其他动作而不必等待连接建立才继续执行后面程序。在调用BeginAccept之前,必须使用Listen方法来侦听是否有连接请求,BeginAccept的函数原型为:

    1. BeginAccept(AsyncCallback AsyncCallback, Ojbect state)
    复制代码

    参数:
    AsyncCallBack:代表回调函数
    state:表示状态信息,必须保证state中包含socket的句柄
      使用BeginAccept的基本流程是:
    (1)创建本地终节点,并新建套接字与本地终节点进行绑定;
    (2)在端口上侦听是否有新的连接请求;
    (3)请求开始接入新的连接,传入Socket的实例或者StateOjbect的实例。
      参考代码:

    1. //定义IP地址
    2. IPAddress local = IPAddress.Parse("127.0,0,1");
    3. IPEndPoint iep = new IPEndPoint(local,13000);
    4. //创建服务器的socket对象
    5. Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    6. server.Bind(iep);
    7. server.Listen(20);
    8. server.BeginAccecpt(new AsyncCallback(Accept),server);
    复制代码

      当BeginAccept()方法调用结束后,一旦新的连接发生,将调用回调函数,而该回调函数必须包括用来结束接入连接操作的EndAccept()方法。
    该方法参数列表为 Socket EndAccept(IAsyncResult iar)
    下面为回调函数的实例:

    1. void Accept(IAsyncResult iar)
    2. {
    3.     //还原传入的原始套接字
    4.     Socket MyServer = (Socket)iar.AsyncState;
    5.     //在原始套接字上调用EndAccept方法,返回新的套接字
    6.     Socket service = MyServer.EndAccept(iar);
    7. }
    复制代码

      至此,服务器端已经准备好了。客户端应通过BeginConnect方法和EndConnect来远程连接主机。在调用BeginConnect方法时必须注册相应的回调函数并且至少传递一个Socket的实例给state参数,以保证EndConnect方法中能使用原始的套接字。下面是一段是BeginConnect的调用:

    1. Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)
    2. IPAddress ip=IPAddress.Parse("127.0.0.1");
    3. IPEndPoint iep=new IPEndPoint(ip,13000);
    4. socket.BeginConnect(iep, new AsyncCallback(Connect),socket);
    复制代码

      EndConnect是一种阻塞方法,用于完成BeginConnect方法的异步连接诶远程主机的请求。在注册了回调函数后必须接收BeginConnect方法返回的IASynccReuslt作为参数。下面为代码演示:

    1. void Connect(IAsyncResult iar)
    2. {
    3.     Socket client=(Socket)iar.AsyncState;
    4.     try
    5.     {
    6.         client.EndConnect(iar);
    7.     }
    8.     catch (Exception e)
    9.     {
    10.         Console.WriteLine(e.ToString());
    11.     }
    12.     finally
    13.     {
    14.     }
    15. }
    复制代码


      除了采用上述方法建立连接之后,也可以采用TcpListener类里面的方法进行连接建立。下面是服务器端对关于TcpListener类使用BeginAccetpTcpClient方法处理一个传入的连接尝试。以下是使用BeginAccetpTcpClient方法和EndAccetpTcpClient方法的代码:

    1. public static void DoBeginAccept(TcpListener listner)
    2. {
    3.     //开始从客户端监听连接
    4.     Console.WriteLine("Waitting for a connection");
    5.     //接收连接
    6.     //开始准备接入新的连接,一旦有新连接尝试则调用回调函数DoAcceptTcpCliet
    7.     listner.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpCliet), listner);
    8. }
    9. //处理客户端的连接
    10. public static void DoAcceptTcpCliet(IAsyncResult iar)
    11. {
    12.     //还原原始的TcpListner对象
    13.     TcpListener listener = (TcpListener)iar.AsyncState;
    14.     //完成连接的动作,并返回新的TcpClient
    15.     TcpClient client = listener.EndAcceptTcpClient(iar);
    16.     Console.WriteLine("连接成功");
    17. }
    复制代码

      代码的处理逻辑为:
    (1)调用BeginAccetpTcpClient方法开开始连接新的连接,当连接视图发生时,回调函数被调用以完成连接操作;
    (2)上面DoAcceptTcpCliet方法通过AsyncState属性获得由BeginAcceptTcpClient传入的listner实例;
    (3)在得到listener对象后,用它调用EndAcceptTcpClient方法,该方法返回新的包含客户端信息的TcpClient。
      BeginConnect方法和EndConnect方法可用于客户端尝试建立与服务端的连接,这里和第一种方法并无区别。下面看实例:

    1. public void doBeginConnect(IAsyncResult iar)
    2. {
    3.     Socket client=(Socket)iar.AsyncState;
    4.     //开始与远程主机进行连接
    5.     client.BeginConnect(serverIP[0],13000,requestCallBack,client);
    6.     Console.WriteLine("开始与服务器进行连接");
    7. }
    8. private void requestCallBack(IAsyncResult iar)
    9. {
    10.     try
    11.     {
    12.         //还原原始的TcpClient对象
    13.         TcpClient client=(TcpClient)iar.AsyncState;
    14.         //
    15.         client.EndConnect(iar);
    16.         Console.WriteLine("与服务器{0}连接成功",client.Client.RemoteEndPoint);
    17.     }
    18.     catch(Exception e)
    19.     {
    20.         Console.WriteLine(e.ToString());
    21.     }
    22.     finally
    23.     {
    24.     }
    25. }
    复制代码

      以上是建立连接的两种方法。可根据需要选择使用。

    3.2 发送与接受数据
      在建立了套接字的连接后,就可以服务器端和客户端之间进行数据通信了。异步套接字用BeginSend和EndSend方法来负责数据的发送。注意在调用BeginSend方法前要确保双方都已经建立连接,否则会出异常。下面演示代码:

    1. private static void Send(Socket handler, String data)
    2. {
    3.     // Convert the string data to byte data using ASCII encoding.     
    4.     byte[] byteData = Encoding.ASCII.GetBytes(data);
    5.     // Begin sending the data to the remote device.     
    6.     handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
    7. }
    8. private static void SendCallback(IAsyncResult ar)
    9. {
    10.     try
    11.     {
    12.         // Retrieve the socket from the state object.     
    13.         Socket handler = (Socket)ar.AsyncState;
    14.         // Complete sending the data to the remote device.     
    15.         int bytesSent = handler.EndSend(ar);
    16.         Console.WriteLine("Sent {0} bytes to client.", bytesSent);
    17.         handler.Shutdown(SocketShutdown.Both);
    18.         handler.Close();
    19.     }
    20.     catch (Exception e)
    21.     {
    22.         Console.WriteLine(e.ToString());
    23.     }
    24. }
    复制代码

      接收数据是通过BeginReceive和EndReceive方法:

    1. private static void Receive(Socket client)
    2. {
    3.     try
    4.     {
    5.         // Create the state object.     
    6.         StateObject state = new StateObject();
    7.         state.workSocket = client;
    8.         // Begin receiving the data from the remote device.     
    9.         client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
    10.     }
    11.     catch (Exception e)
    12.     {
    13.         Console.WriteLine(e.ToString());
    14.     }
    15. }
    16. private static void ReceiveCallback(IAsyncResult ar)
    17. {
    18.     try
    19.     {
    20.         // Retrieve the state object and the client socket     
    21.         // from the asynchronous state object.     
    22.         StateObject state = (StateObject)ar.AsyncState;
    23.         Socket client = state.workSocket;
    24.         // Read data from the remote device.     
    25.         int bytesRead = client.EndReceive(ar);
    26.         if (bytesRead > 0)
    27.         {
    28.             // There might be more data, so store the data received so far.     
    29.             state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
    30.             // Get the rest of the data.     
    31.             client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
    32.         }
    33.         else
    34.         {
    35.             // All the data has arrived; put it in response.     
    36.             if (state.sb.Length > 1)
    37.             {
    38.                 response = state.sb.ToString();
    39.             }
    40.             // Signal that all bytes have been received.     
    41.             receiveDone.Set();
    42.         }
    43.     }
    44.     catch (Exception e)
    45.     {
    46.         Console.WriteLine(e.ToString());
    47.     }
    48. }
    复制代码

      上述代码的处理逻辑为:
    (1)首先处理连接的回调函数里得到的通讯套接字client,接着开始接收数据;
    (2)当数据发送到缓冲区中,BeginReceive方法试图从buffer数组中读取长度为buffer.length的数据块,并返回接收到的数据量bytesRead。最后接收并打印数据。
      
      除了上述方法外,还可以使用基于NetworkStream相关的异步发送和接收方法,下面是基于NetworkStream相关的异步发送和接收方法的使用介绍。
      NetworkStream使用BeginRead和EndRead方法进行读操作,使用BeginWreite和EndWrete方法进行写操作,下面看实例:


    1. static void DataHandle(TcpClient client)
    2. {
    3.   TcpClient tcpClient = client;
    4.   //使用TcpClient的GetStream方法获取网络流
    5.   NetworkStream ns = tcpClient.GetStream();
    6.   //检查网络流是否可读
    7.   if(ns.CanRead)
    8.   {
    9.     //定义缓冲区
    10.     byte[] read = new byte[1024];
    11.     ns.BeginRead(read,0,read.Length,new AsyncCallback(myReadCallBack),ns);  
    12.   }
    13.   else
    14.   {
    15.     Console.WriteLine("无法从网络中读取流数据");
    16.   }
    17. }
    18. public static void myReadCallBack(IAsyncResult iar)
    19. {
    20.     NetworkStream ns = (NetworkStream)iar.AsyncState;
    21.     byte[] read = new byte[1024];
    22.     String data = "";
    23.     int recv;
    24.     recv = ns.EndRead(iar);
    25.     data = String.Concat(data, Encoding.ASCII.GetString(read, 0, recv));
    26.     //接收到的消息长度可能大于缓冲区总大小,反复循环直到读完为止
    27.     while (ns.DataAvailable)
    28.     {
    29.         ns.BeginRead(read, 0, read.Length, new AsyncCallback(myReadCallBack), ns);
    30.     }
    31.     //打印
    32.     Console.WriteLine("您收到的信息是" + data);
    33. }
    复制代码

    3.3 程序阻塞与异步中的同步问题
      .Net里提供了EventWaitHandle类来表示一个线程的同步事件。EventWaitHandle即事件等待句柄,他允许线程通过操作系统互发信号和等待彼此的信号来达到线程同步的目的。这个类有2个子类,分别为AutoRestEevnt(自动重置)和ManualRestEvent(手动重置)。下面是线程同步的几个方法:
    (1)Rset方法:将事件状态设为非终止状态,导致线程阻塞。这里的线程阻塞是指允许其他需要等待的线程进行阻塞即让含WaitOne()方法的线程阻塞;
    (2)Set方法:将事件状态设为终止状态,允许一个或多个等待线程继续。该方法发送一个信号给操作系统,让处于等待的某个线程从阻塞状态转换为继续运行,即WaitOne方法的线程不在阻塞;
    (3)WaitOne方法:阻塞当前线程,直到当前的等待句柄收到信号。此方法将一直使本线程处于阻塞状态直到收到信号为止,即当其他非阻塞进程调用set方法时可以继续执行。


    1. public static void StartListening()
    2. {
    3.     // Data buffer for incoming data.     
    4.     byte[] bytes = new Byte[1024];
    5.     // Establish the local endpoint for the socket.     
    6.     // The DNS name of the computer     
    7.     // running the listener is "host.contoso.com".     
    8.     //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    9.     //IPAddress ipAddress = ipHostInfo.AddressList[0];
    10.     IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    11.     IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    12.     // Create a TCP/IP socket.     
    13.     Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
    14.     // Bind the socket to the local     
    15.     //endpoint and listen for incoming connections.     
    16.     try
    17.     {
    18.         listener.Bind(localEndPoint);
    19.         listener.Listen(100);
    20.         while (true)
    21.         {
    22.             // Set the event to nonsignaled state.     
    23.             allDone.Reset();
    24.             // Start an asynchronous socket to listen for connections.     
    25.             Console.WriteLine("Waiting for a connection...");
    26.             listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
    27.             // Wait until a connection is made before continuing.     
    28.             allDone.WaitOne();
    29.         }
    30.     }
    31.     catch (Exception e)
    32.     {
    33.         Console.WriteLine(e.ToString());
    34.     }
    35.     Console.WriteLine("\nPress ENTER to continue...");
    36.     Console.Read();
    37. }
    复制代码


      上述代码的逻辑为:
    (1)试用了ManualRestEvent对象创建一个等待句柄,在调用BeginAccept方法前使用Rest方法允许其他线程阻塞;
    (2)为了防止在连接完成之前对套接字进行读写操作,务必要在BeginAccept方法后调用WaitOne来让线程进入阻塞状态。

      当有连接接入后系统会自动调用会调用回调函数,所以当代码执行到回调函数时说明连接已经成功,并在函数的第一句就调用Set方法让处于等待的线程可以继续执行。

    四、实例
      下面是一个实例,客户端请求连接,服务器端侦听端口,当连接建立之后,服务器发送字符串给客户端,客户端收到后并回发给服务器端。
    服务器端代码:




    View Code

    1. using System;
    2. using System.Net;
    3. using System.Net.Sockets;
    4. using System.Text;
    5. using System.Threading;
    6. // State object for reading client data asynchronously     
    7. public class StateObject
    8. {
    9.     // Client socket.     
    10.     public Socket workSocket = null;
    11.     // Size of receive buffer.     
    12.     public const int BufferSize = 1024;
    13.     // Receive buffer.     
    14.     public byte[] buffer = new byte[BufferSize];
    15.     // Received data string.     
    16.     public StringBuilder sb = new StringBuilder();
    17. }
    18. public class AsynchronousSocketListener
    19. {
    20.     // Thread signal.     
    21.     public static ManualResetEvent allDone = new ManualResetEvent(false);
    22.     public AsynchronousSocketListener()
    23.     {
    24.     }
    25.     public static void StartListening()
    26.     {
    27.         // Data buffer for incoming data.     
    28.         byte[] bytes = new Byte[1024];
    29.         // Establish the local endpoint for the socket.     
    30.         // The DNS name of the computer     
    31.         // running the listener is "host.contoso.com".     
    32.         //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    33.         //IPAddress ipAddress = ipHostInfo.AddressList[0];
    34.         IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    35.         IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    36.         // Create a TCP/IP socket.     
    37.         Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
    38.         // Bind the socket to the local     
    39.         //endpoint and listen for incoming connections.     
    40.         try
    41.         {
    42.             listener.Bind(localEndPoint);
    43.             listener.Listen(100);
    44.             while (true)
    45.             {
    46.                 // Set the event to nonsignaled state.     
    47.                 allDone.Reset();
    48.                 // Start an asynchronous socket to listen for connections.     
    49.                 Console.WriteLine("Waiting for a connection...");
    50.                 listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
    51.                 // Wait until a connection is made before continuing.     
    52.                 allDone.WaitOne();
    53.             }
    54.         }
    55.         catch (Exception e)
    56.         {
    57.             Console.WriteLine(e.ToString());
    58.         }
    59.         Console.WriteLine("\nPress ENTER to continue...");
    60.         Console.Read();
    61.     }
    62.     public static void AcceptCallback(IAsyncResult ar)
    63.     {
    64.         // Signal the main thread to continue.     
    65.         allDone.Set();
    66.         // Get the socket that handles the client request.     
    67.         Socket listener = (Socket)ar.AsyncState;
    68.         Socket handler = listener.EndAccept(ar);
    69.         // Create the state object.     
    70.         StateObject state = new StateObject();
    71.         state.workSocket = handler;
    72.         handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
    73.     }
    74.     public static void ReadCallback(IAsyncResult ar)
    75.     {
    76.         String content = String.Empty;
    77.         // Retrieve the state object and the handler socket     
    78.         // from the asynchronous state object.     
    79.         StateObject state = (StateObject)ar.AsyncState;
    80.         Socket handler = state.workSocket;
    81.         // Read data from the client socket.     
    82.         int bytesRead = handler.EndReceive(ar);
    83.         if (bytesRead > 0)
    84.         {
    85.             // There might be more data, so store the data received so far.     
    86.             state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
    87.             // Check for end-of-file tag. If it is not there, read     
    88.             // more data.     
    89.             content = state.sb.ToString();
    90.             if (content.IndexOf("<EOF>") > -1)
    91.             {
    92.                 // All the data has been read from the     
    93.                 // client. Display it on the console.     
    94.                 Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
    95.                 // Echo the data back to the client.     
    96.                 Send(handler, content);
    97.             }
    98.             else
    99.             {
    100.                 // Not all data received. Get more.     
    101.                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
    102.             }
    103.         }
    104.     }
    105.     private static void Send(Socket handler, String data)
    106.     {
    107.         // Convert the string data to byte data using ASCII encoding.     
    108.         byte[] byteData = Encoding.ASCII.GetBytes(data);
    109.         // Begin sending the data to the remote device.     
    110.         handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
    111.     }
    112.     private static void SendCallback(IAsyncResult ar)
    113.     {
    114.         try
    115.         {
    116.             // Retrieve the socket from the state object.     
    117.             Socket handler = (Socket)ar.AsyncState;
    118.             // Complete sending the data to the remote device.     
    119.             int bytesSent = handler.EndSend(ar);
    120.             Console.WriteLine("Sent {0} bytes to client.", bytesSent);
    121.             handler.Shutdown(SocketShutdown.Both);
    122.             handler.Close();
    123.         }
    124.         catch (Exception e)
    125.         {
    126.             Console.WriteLine(e.ToString());
    127.         }
    128.     }
    129.     public static int Main(String[] args)
    130.     {
    131.         StartListening();
    132.         return 0;
    133.     }
    134. }
    复制代码



    客户端代码:




    View Code

    1. using System;
    2. using System.Net;
    3. using System.Net.Sockets;
    4. using System.Threading;
    5. using System.Text;
    6. // State object for receiving data from remote device.     
    7. public class StateObject
    8. {
    9.     // Client socket.     
    10.     public Socket workSocket = null;
    11.     // Size of receive buffer.     
    12.     public const int BufferSize = 256;
    13.     // Receive buffer.     
    14.     public byte[] buffer = new byte[BufferSize];
    15.     // Received data string.     
    16.     public StringBuilder sb = new StringBuilder();
    17. }
    18. public class AsynchronousClient
    19. {
    20.     // The port number for the remote device.     
    21.     private const int port = 11000;
    22.     // ManualResetEvent instances signal completion.     
    23.     private static ManualResetEvent connectDone = new ManualResetEvent(false);
    24.     private static ManualResetEvent sendDone = new ManualResetEvent(false);
    25.     private static ManualResetEvent receiveDone = new ManualResetEvent(false);
    26.     // The response from the remote device.     
    27.     private static String response = String.Empty;
    28.     private static void StartClient()
    29.     {
    30.         // Connect to a remote device.     
    31.         try
    32.         {
    33.             // Establish the remote endpoint for the socket.     
    34.             // The name of the     
    35.             // remote device is "host.contoso.com".     
    36.             //IPHostEntry ipHostInfo = Dns.Resolve("user");
    37.             //IPAddress ipAddress = ipHostInfo.AddressList[0];
    38.             IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    39.             IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
    40.             // Create a TCP/IP socket.     
    41.             Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    42.             // Connect to the remote endpoint.     
    43.             client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
    44.             connectDone.WaitOne();
    45.             // Send test data to the remote device.     
    46.             Send(client, "This is a test<EOF>");
    47.             sendDone.WaitOne();
    48.             // Receive the response from the remote device.     
    49.             Receive(client);
    50.             receiveDone.WaitOne();
    51.             // Write the response to the console.     
    52.             Console.WriteLine("Response received : {0}", response);
    53.             // Release the socket.     
    54.             client.Shutdown(SocketShutdown.Both);
    55.             client.Close();
    56.             Console.ReadLine();
    57.         }
    58.         catch (Exception e)
    59.         {
    60.             Console.WriteLine(e.ToString());
    61.         }
    62.     }
    63.     private static void ConnectCallback(IAsyncResult ar)
    64.     {
    65.         try
    66.         {
    67.             // Retrieve the socket from the state object.     
    68.             Socket client = (Socket)ar.AsyncState;
    69.             // Complete the connection.     
    70.             client.EndConnect(ar);
    71.             Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());
    72.             // Signal that the connection has been made.     
    73.             connectDone.Set();
    74.         }
    75.         catch (Exception e)
    76.         {
    77.             Console.WriteLine(e.ToString());
    78.         }
    79.     }
    80.     private static void Receive(Socket client)
    81.     {
    82.         try
    83.         {
    84.             // Create the state object.     
    85.             StateObject state = new StateObject();
    86.             state.workSocket = client;
    87.             // Begin receiving the data from the remote device.     
    88.             client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
    89.         }
    90.         catch (Exception e)
    91.         {
    92.             Console.WriteLine(e.ToString());
    93.         }
    94.     }
    95.     private static void ReceiveCallback(IAsyncResult ar)
    96.     {
    97.         try
    98.         {
    99.             // Retrieve the state object and the client socket     
    100.             // from the asynchronous state object.     
    101.             StateObject state = (StateObject)ar.AsyncState;
    102.             Socket client = state.workSocket;
    103.             // Read data from the remote device.     
    104.             int bytesRead = client.EndReceive(ar);
    105.             if (bytesRead > 0)
    106.             {
    107.                 // There might be more data, so store the data received so far.     
    108.                 state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
    109.                 // Get the rest of the data.     
    110.                 client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
    111.             }
    112.             else
    113.             {
    114.                 // All the data has arrived; put it in response.     
    115.                 if (state.sb.Length > 1)
    116.                 {
    117.                     response = state.sb.ToString();
    118.                 }
    119.                 // Signal that all bytes have been received.     
    120.                 receiveDone.Set();
    121.             }
    122.         }
    123.         catch (Exception e)
    124.         {
    125.             Console.WriteLine(e.ToString());
    126.         }
    127.     }
    128.     private static void Send(Socket client, String data)
    129.     {
    130.         // Convert the string data to byte data using ASCII encoding.     
    131.         byte[] byteData = Encoding.ASCII.GetBytes(data);
    132.         // Begin sending the data to the remote device.     
    133.         client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
    134.     }
    135.     private static void SendCallback(IAsyncResult ar)
    136.     {
    137.         try
    138.         {
    139.             // Retrieve the socket from the state object.     
    140.             Socket client = (Socket)ar.AsyncState;
    141.             // Complete sending the data to the remote device.     
    142.             int bytesSent = client.EndSend(ar);
    143.             Console.WriteLine("Sent {0} bytes to server.", bytesSent);
    144.             // Signal that all bytes have been sent.     
    145.             sendDone.Set();
    146.         }
    147.         catch (Exception e)
    148.         {
    149.             Console.WriteLine(e.ToString());
    150.         }
    151.     }
    152.     public static int Main(String[] args)
    153.     {
    154.         StartClient();
    155.         return 0;
    156.     }
    157. }
    复制代码




    五、实验结果

    图1 服务器端界面

    图2 客户端界面







    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-27 00:17 , Processed in 0.518843 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表