服务器端
TCPServer
1、使用的通讯通道:socket
2、用到的基本功能:
Bind,
Listen,
BeginAccept
EndAccept
BeginReceive
EndReceive
3、函数参数说明
Socket listener
=
new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
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);
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);
new AsyncCallback(ReadCallback), state);
接收的字节,0,字节长度,0,接收时调用的回调函数,接收行为的容器。
========
容器的结构类型为:
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
容器至少为一个socket类型。
===============
//
Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
int bytesRead = handler.EndReceive(ar);
完成一次连接。数据存储在state.buffer里,bytesRead为读取的长度。
handler.BeginSend(byteData,
0
, byteData.Length,
0
,
new AsyncCallback(SendCallback), handler);
new AsyncCallback(SendCallback), handler);
发送数据byteData,回调函数SendCallback。容器handler
int
bytesSent
=
handler.EndSend(ar);
发送完毕,bytesSent发送字节数。
4 程序结构
主程序:
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:
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: