C# Socket异步通信

C# Socket异步通信

 

TCPServer

1、使用的通讯通道:socket

2、用到的基本功能:

Bind,

Listen,

BeginAccept

EndAccept

BeginReceive

EndReceive

3、函数参数说明

Socket listener = new Socket(AddressFamily.InterNetwork,

SocketType.Stream, ProtocolType.Tcp);

新建socket所使用的参数均为系统预定义的量,直接选取使用。

listener.Bind(localEndPoint);

localEndPoint 表示一个定义完整的终端,包括IP和端口信息。

//new IPEndPoint(IPAddress,port)

//IPAdress.Parse(“192.168.1.3”)

listener.Listen(100);

监听

listener.BeginAccept(

new AsyncCallback(AcceptCallback),

listener);

AsyncCallback(AcceptCallback),一旦连接上后的回调函数为AcceptCallback。当系统调用这个函数时,自动赋予的输入参数为IAsyncResoult类型变量ar。

listener,连接行为的容器。

Socket handler = listener.EndAccept(ar);

完成连接,返回此时的socket通道。

handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,

new AsyncCallback(ReadCallback), state);

接收的字节,0,字节长度,0,接收时调用的回调函数,接收行为的容器。

========

容器的结构类型为:

Code

 

publicclass StateObject
{
// Client socket.
public Socket workSocket =null;
// Size of receive buffer.
publicconstint BufferSize =1024;
// Receive buffer.
publicbyte[] buffer =newbyte[BufferSize];
// Received data string.
public StringBuilder sb =new StringBuilder();
}
容器至少为一个socket类型。

===============

// Read data from the client socket.

int bytesRead = handler.EndReceive(ar);

完成一次连接。数据存储在state.buffer里,bytesRead为读取的长度。

handler.BeginSend(byteData, 0, byteData.Length, 0,

new AsyncCallback(SendCallback), handler);

发送数据byteData,回调函数SendCallback。容器handler

int bytesSent = handler.EndSend(ar);

发送完毕,bytesSent发送字节数。

4 程序结构

主程序:

Code

 

byte[] bytes =new Byte[1024];
IPAddress ipAddress = IPAddress.Parse(“192.168.1.104”);
IPEndPoint localEndPoint =new IPEndPoint(ipAddress, 11000);

// 生成一个TCP的socket
Socket listener =new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

listener.Bind(localEndPoint);
listener.Listen(100);

while (true)
{

// Set the event to nonsignaled state.
allDone.Reset();

//开启异步监听socket
Console.WriteLine(“Waiting for a connection”);
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);

// 让程序等待,直到连接任务完成。在AcceptCallback里的适当位置放置allDone.Set()语句.
allDone.WaitOne();
}

Console.WriteLine(“\nPress ENTER to continue”);
Console.Read();
连接行为回调函数AcceptCallback:

Code

public static void AcceptCallback(IAsyncResult ar)

{

//添加此命令,让主线程继续.

allDone.Set();

// 获取客户请求的socket

Socket listener = (Socket)ar.AsyncState;

Socket handler = listener.EndAccept(ar);

// 造一个容器,并用于接收命令.

StateObject state = new StateObject();

state.workSocket = handler;

handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,

new AsyncCallback(ReadCallback), state);

}

读取行为的回调函数ReadCallback:

Code

public static void ReadCallback(IAsyncResult ar)

{

String content = String.Empty;

// 从异步state对象中获取state和socket对象.

StateObject state = (StateObject)ar.AsyncState;

Socket handler = state.workSocket;

// 从客户socket读取数据.

int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0)

{

// 如果接收到数据,则存起来

state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

// 检查是否有结束标记,如果没有则继续读取

content = state.sb.ToString();

if (content.IndexOf(“<EOF>”) > -1)

{

//所有数据读取完毕.

Console.WriteLine(“Read {0} bytes from socket. \n Data : {1}”,

content.Length, content);

// 给客户端响应.

Send(handler, content);

}

else

{

// 接收未完成,继续接收.

handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,

new AsyncCallback(ReadCallback), state);

}

}

}

发送消息给客户端:

Code

private static void Send(Socket handler, String data)

{

// 消息格式转换.

byte[] byteData = Encoding.ASCII.GetBytes(data);

// 开始发送数据给远程目标.

handler.BeginSend(byteData, 0, byteData.Length, 0,

new AsyncCallback(SendCallback), handler);

}

private static void SendCallback(IAsyncResult ar)

{

 

// 从state对象获取socket.

Socket handler = (Socket)ar.AsyncState;

//完成数据发送

int bytesSent = handler.EndSend(ar);

Console.WriteLine(“Sent {0} bytes to client.”, bytesSent);

handler.Shutdown(SocketShutdown.Both);

handler.Close();

}

在各种行为的回调函数中,所对应的socket都从输入参数的AsyncState属性获得。使用(Socket)或者(StateObject)进行强制转换。BeginReceive函数使用的容器为state,因为它需要存放传送的数据。

而其余接收或发送函数的容器为socket也可。

完整代码

 

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

标签