1、IPAddress local = IPAddress.Parse(127.0,0,1);IPEndPoint iep = new IPEndPoint(local,13000);/创建服务器的socket对象Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);server.Bind(iep);server.Listen(20);server.BeginAccecpt(new AsyncCallback(Accept),server);当BeginAccept()方法
2、调用结束后,一旦新的连接发生,将调用回调函数,而该回调函数必须包括用来结束接入连接操作的EndAccept()方法。该方法参数列表为 Socket EndAccept(IAsyncResult iar)下面为回调函数的实例:void Accept(IAsyncResult iar) /还原传入的原始套接字 Socket MyServer = (Socket)iar.AsyncState; /在原始套接字上调用EndAccept方法,返回新的套接字 Socket service = MyServer.EndAccept(iar);至此,服务器端已经准备好了。客户端应通过BeginConnect方
3、法和EndConnect来远程连接主机。在调用BeginConnect方法时必须注册相应的回调函数并且至少传递一个Socket的实例给state参数,以保证EndConnect方法中能使用原始的套接字。下面是一段是BeginConnect的调用:Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)IPAddress ip=IPAddress.Parse(127.0.0.1IPEndPoint iep=new IPEndPoint(ip,13000);socket.Begin
4、Connect(iep, new AsyncCallback(Connect),socket);EndConnect是一种阻塞方法,用于完成BeginConnect方法的异步连接诶远程主机的请求。在注册了回调函数后必须接收BeginConnect方法返回的IASynccReuslt作为参数。下面为代码演示:void Connect(IAsyncResult iar) Socket client=(Socket)iar.AsyncState; try client.EndConnect(iar); catch (Exception e) Console.WriteLine(e.ToString(
5、); finally除了采用上述方法建立连接之后,也可以采用TcpListener类里面的方法进行连接建立。下面是服务器端对关于TcpListener类使用BeginAccetpTcpClient方法处理一个传入的连接尝试。以下是使用BeginAccetpTcpClient方法和EndAccetpTcpClient方法的代码:public static void DoBeginAccept(TcpListener listner) /开始从客户端监听连接 Console.WriteLine(Waitting for a connection /接收连接 /开始准备接入新的连接,一旦有新连接尝试
6、则调用回调函数DoAcceptTcpCliet listner.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpCliet), listner);/处理客户端的连接public static void DoAcceptTcpCliet(IAsyncResult iar) /还原原始的TcpListner对象 TcpListener listener = (TcpListener)iar.AsyncState; /完成连接的动作,并返回新的TcpClient TcpClient client = listener.EndAcceptTcpCli
7、ent(iar);连接成功代码的处理逻辑为:(1)调用BeginAccetpTcpClient方法开开始连接新的连接,当连接视图发生时,回调函数被调用以完成连接操作;(2)上面DoAcceptTcpCliet方法通过AsyncState属性获得由BeginAcceptTcpClient传入的listner实例;(3)在得到listener对象后,用它调用EndAcceptTcpClient方法,该方法返回新的包含客户端信息的TcpClient。BeginConnect方法和EndConnect方法可用于客户端尝试建立与服务端的连接,这里和第一种方法并无区别。下面看实例:public void
8、doBeginConnect(IAsyncResult iar) /开始与远程主机进行连接 client.BeginConnect(serverIP0,13000,requestCallBack,client);开始与服务器进行连接private void requestCallBack(IAsyncResult iar) /还原原始的TcpClient对象 TcpClient client=(TcpClient)iar.AsyncState; /与服务器0连接成功,client.Client.RemoteEndPoint); catch(Exception e)以上是建立连接的两种方法。可根
9、据需要选择使用。3.2 发送与接受数据在建立了套接字的连接后,就可以服务器端和客户端之间进行数据通信了。异步套接字用BeginSend和EndSend方法来负责数据的发送。注意在调用BeginSend方法前要确保双方都已经建立连接,否则会出异常。下面演示代码:private static void Send(Socket handler, String data) / Convert the string data to byte data using ASCII encoding. byte byteData = Encoding.ASCII.GetBytes(data); / Begin
10、sending the data to the remote device. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);private static void SendCallback(IAsyncResult ar) / Retrieve the socket from the state object. Socket handler = (Socket)ar.AsyncState; / Complete sending the data to th
11、e remote device. int bytesSent = handler.EndSend(ar);Sent 0 bytes to client., bytesSent); handler.Shutdown(SocketShutdown.Both); handler.Close();接收数据是通过BeginReceive和EndReceive方法:private static void Receive(Socket client) / Create the state object. StateObject state = new StateObject(); state.workSoc
12、ket = client; / Begin receiving the data from the remote device. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);private static void ReceiveCallback(IAsyncResult ar) / Retrieve the state object and the client socket / from the asynchronous s
13、tate object. StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; / Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead 0) / There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buf
14、fer, 0, bytesRead); / Get the rest of the data. else / All the data has arrived; put it in response. if (state.sb.Length 1) response = state.sb.ToString(); / Signal that all bytes have been received. receiveDone.Set();上述代码的处理逻辑为:(1)首先处理连接的回调函数里得到的通讯套接字client,接着开始接收数据;(2)当数据发送到缓冲区中,BeginReceive方法试图从b
15、uffer数组中读取长度为buffer.length的数据块,并返回接收到的数据量bytesRead。最后接收并打印数据。除了上述方法外,还可以使用基于NetworkStream相关的异步发送和接收方法,下面是基于NetworkStream相关的异步发送和接收方法的使用介绍。NetworkStream使用BeginRead和EndRead方法进行读操作,使用BeginWreite和EndWrete方法进行写操作,下面看实例:static void DataHandle(TcpClient client) TcpClient tcpClient = client; /使用TcpClient的Ge
16、tStream方法获取网络流 NetworkStream ns = tcpClient.GetStream(); /检查网络流是否可读 if(ns.CanRead) /定义缓冲区 byte read = new byte1024; ns.BeginRead(read,0,read.Length,new AsyncCallback(myReadCallBack),ns); 无法从网络中读取流数据public static void myReadCallBack(IAsyncResult iar) NetworkStream ns = (NetworkStream)iar.AsyncState;
17、String data = ; int recv; recv = ns.EndRead(iar); data = String.Concat(data, Encoding.ASCII.GetString(read, 0, recv); /接收到的消息长度可能大于缓冲区总大小,反复循环直到读完为止 while (ns.DataAvailable) ns.BeginRead(read, 0, read.Length, new AsyncCallback(myReadCallBack), ns); /打印您收到的信息是 + data);3.3 程序阻塞与异步中的同步问题.Net里提供了EventWa
18、itHandle类来表示一个线程的同步事件。EventWaitHandle即事件等待句柄,他允许线程通过操作系统互发信号和等待彼此的信号来达到线程同步的目的。这个类有2个子类,分别为AutoRestEevnt(自动重置)和ManualRestEvent(手动重置)。下面是线程同步的几个方法:(1)Rset方法:将事件状态设为非终止状态,导致线程阻塞。这里的线程阻塞是指允许其他需要等待的线程进行阻塞即让含WaitOne()方法的线程阻塞;(2)Set方法:将事件状态设为终止状态,允许一个或多个等待线程继续。该方法发送一个信号给操作系统,让处于等待的某个线程从阻塞状态转换为继续运行,即WaitOn
19、e方法的线程不在阻塞;(3)WaitOne方法:阻塞当前线程,直到当前的等待句柄收到信号。此方法将一直使本线程处于阻塞状态直到收到信号为止,即当其他非阻塞进程调用set方法时可以继续执行。public static void StartListening() / Data buffer for incoming data. byte bytes = new Byte1024; / Establish the local endpoint for the socket. / The DNS name of the computer / running the listener is . /IPH
20、ostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName(); /IPAddress ipAddress = ipHostInfo.AddressList0; IPAddress ipAddress = IPAddress.Parse( IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); / Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream
21、, ProtocolType.Tcp); / Bind the socket to the local /endpoint and listen for incoming connections. listener.Bind(localEndPoint); listener.Listen(100); while (true) / Set the event to nonsignaled state. allDone.Reset(); / Start an asynchronous socket to listen for connections. Waiting for a connectio
22、n. listener.BeginAccept(new AsyncCallback(AcceptCallback),listener); / Wait until a connection is made before continuing. allDone.WaitOne();nPress ENTER to continue. Console.Read();上述代码的逻辑为:(1)试用了ManualRestEvent对象创建一个等待句柄,在调用BeginAccept方法前使用Rest方法允许其他线程阻塞;(2)为了防止在连接完成之前对套接字进行读写操作,务必要在BeginAccept方法后调
23、用WaitOne来让线程进入阻塞状态。当有连接接入后系统会自动调用会调用回调函数,所以当代码执行到回调函数时说明连接已经成功,并在函数的第一句就调用Set方法让处于等待的线程可以继续执行。四、实例下面是一个实例,客户端请求连接,服务器端侦听端口,当连接建立之后,服务器发送字符串给客户端,客户端收到后并回发给服务器端。服务器端代码:using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;/ State object for reading client data
24、 asynchronously public class StateObject / Client socket. public Socket workSocket = null; / Size of receive buffer. public const int BufferSize = 1024; / Receive buffer. public byte buffer = new byteBufferSize; / Received data string. public StringBuilder sb = new StringBuilder();public class AsynchronousSocketListener / Thread signal. public static ManualResetEvent allDone = new ManualResetEvent(false); public AsynchronousSocketListener() public static void StartListening() IPE
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1