C# Socket基础(一)之启动异步服务监听
本文主要是以代码为主。.NET技术交流群 199281001 .欢迎加入。
//通知一个或多个正在等待的线程已发生事件。
ManualResetEvent manager = new ManualResetEvent(false);
1 //负责监听的套接字
private Socket socketServer;
2 /// <summary>
3 /// 启动服务
4 /// </summary>
5 private void CreateSocketService()
6 {
7 try
8 {
9 //获取IP
10 var address = IPAddress.Parse(txtIP.Text.Trim());
11 //创建一个包含ip port 的网络节点对象
12 var ipPoint = new IPEndPoint(address, Convert.ToInt32(txtPort.Text.Trim()));
13 //创建一个套接字socket,参数(IP4寻址协议,流式连接,使用TCP协议传输数据)
14 socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
15 //将负责监听的套接字绑定到唯一的IP和端口上
16 socketServer.Bind(ipPoint);
17 //设置监听队列的长度,同时100个队列
18 socketServer.Listen(100);
19 //线程开始监听客户端的请求
20 threadService = new Thread(StartSocketService);
21 //设置线程为后台线程
22 threadService.IsBackground = true;
23 //启动线程
24 threadService.Start();
25 //显示消息
26 ShowMsg("服务器监听开启成功!");
27
28
29 }
30 catch (Exception e)
31 {
32
33 ShowMsg(e.Message);
34 }
35 }
1 /// <summary>
2 /// 启动服务监听
3 /// </summary>
4 private void StartSocketService()
5 {
6 while (true)
7 {
8 try
9 {
//将事件状态设置为非终止状态,导致线程阻止
10 manager.Reset();
11 //开始监听客户端的连接请求
12 var args = new SocketAsyncEventArgs();
13 args.Completed += args_Completed;
14 socketServer.AcceptAsync(args);
//阻止当前线程,直到当前 WaitHandle 收到信号。
15 manager.WaitOne();
16 }
17 catch (Exception ex)
18 {
19
20 ShowMsg(ex.Message);
21 break;
22 }
23 }
24 }
1 void args_Completed(object sender, SocketAsyncEventArgs e)
2 {
3 //监听完成客户端的请求,一但监听到返回新的套接字
4 var clientSocket = e.AcceptSocket;
5 //启动线程获取客户端发来的消息
6 if (clientSocket == null) return;
//开始接受消息.......
7 //该函数未写完,第二篇补全
8 }
1 void ShowMsg(string message)
2 {
3 //显示消息
4 txtConneMsg.AppendText("\r\n" + DateTime.Now + "\r\n\r\n" + message + "\r\n");
5 }
ok 服务监听就启动成功了,正等待客户端连接。
ManualResetEvent reviceManager = new ManualResetEvent(false);
1 public void args_Completed(object sender, SocketAsyncEventArgs e)
2 {
3 //监听完成客户端的请求,一但监听到返回新的套接字
4 var clientSocket = e.AcceptSocket;
5
6 if (clientSocket == null) return;
7 //启动线程获取客户端发来的消息
8 //这部分为接收消息
9 var t = new Thread(GetClientMsg);
10 //设置线程为后台线程
11 t.IsBackground = true;
12 //启动线程
13 t.Start(clientSocket);
14 //显示信息
15 ShowMsg(clientSocket.RemoteEndPoint + "上线了");
16 //将事件状态设置为终止状态,允许一个或多个等待线程继续
17 manager.Set();
18 }
建议对照 C# Socket基础(一)之启动异步服务侦听 来看。
1 private void GetClientMsg(object socket)
2 {
3 var socketClient = socket as Socket;
4 if (socketClient == null) return;
5 while (true)
6 {
7 try
8 {
9 reviceManager.Reset();
10 var bytes = new byte[1024 * 1024 * 4];
11 var receiveArgs = new SocketAsyncEventArgs();
//设置缓冲区
12 receiveArgs.SetBuffer(bytes, 0, bytes.Length);
13 receiveArgs.Completed += receiveArgs_Completed;
//开始异步接收
14 socketClient.ReceiveAsync(receiveArgs);
15 reviceManager.WaitOne();
16 }
17 catch (Exception ex)
18 {
19
20 //显示异常消息
21 ShowMsg(ex.Message);
22 }
}
}
接收消息完成回调事件
1 void receiveArgs_Completed(object sender, SocketAsyncEventArgs e)
2 {
3 var socketClient = sender as Socket;
4 var bytes = e.Buffer;
5 ShowMsg(socketClient.RemoteEndPoint + "说:" + System.Text.Encoding.UTF8.GetString(bytes));
6 reviceManager.Set();
7 }
又与大家见面,看不懂的随时问。
1 private Thread threadClient;//客户端线程
2 private Socket socketClient;//客户端套接字
3 /// <summary>
4 /// 创建套接字连接到服务端
5 /// </summary>
6 private void CreateSocketConnection()
7 {
8 try
9 {
10 //创建一个客户端的套接字 参数(IP4寻址协议,流连接方式,TCP数据传输协议)
11 socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
12 //获取IP
13 IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
14 //创建一个包含IP和端口号的网络节点对象
15 IPEndPoint ipPoint = new IPEndPoint(address, Convert.ToInt32(txtPort.Text.Trim()));
16 // 连接服务端
17 socketClient.Connect(ipPoint);
18 //创建一个线程,接受服务端发来的数据
19 threadClient = new Thread(ReceiveService);
20 //设置线程为后台线程
21 threadClient.IsBackground = true;
22 //启动线程连接服务端
23 threadClient.Start();
24 //显示消息
25 ShowMsg("与服务器" + txtIP.Text.Trim() + ":" + txtPort.Text + "成功建立连接!");
26
27 }
28 catch (Exception)
29 {
30
31 ShowMsg(txtIP.Text.Trim() + ":" + txtPort.Text + "服务器未启动!");
32
33 }
34
35 }
客户端接收消息
private void ReceiveService()
{
while (true)
{
try
{
int num = -1;
var b = new byte[1024 * 1024 * 4];
int length = socketClient.Receive(b);
var msg = System.Text.Encoding.UTF8.GetString(b,0,length);
ShowMsg(socketClient.RemoteEndPoint.ToString() + "对您: " + msg);
}
catch (Exception ex)
{
ShowMsg(ex.Message);
break;
}
}
}
1 private void ShowMsg(string msg)
2 {
3 txtConneMsg.AppendText("\r\n" + DateTime.Now + "\r\n\r\n" + msg + "\r\n");
4 }
客户端:
服务器:
客户端接收到消息:
private Socket socketClient;//客户端套接字,关于实例化请参考C# Socket基础(三)之客户端连接服务器和接收消息
客户端发送消息
1 /// <summary>
2 /// 发送数据到服务端
3 /// </summary>
4 private void Send()
5 {
6 if (socketClient == null)
7 {
8
9 ShowMsg("服务器未启动!");
10 return;
11 }
12 byte[] b = System.Text.Encoding.UTF8.GetBytes(txtSend.Text.Trim());
13 //客户端向服务器发送消息
14 socketClient.Send(b);
15 //清空文本
16
17 ShowMsg("您对" + socketClient.RemoteEndPoint.ToString() + "说:" + txtSend.Text.Trim());
18 txtSend.Text = "";
19 }
关于 ShowMsg(string message);是自定义的函数,在C# Socket基础(一)之启动异步服务侦听
好了,到这里就要告一段落了,实现了基本的客户端和服务器采用TCP协议通信。
看看效果吧:
客户端:
服务器: