跟上篇一样,通过C#套接字的助手类来编程同样分服务端和客户端。
一、服务端侦听模式
1、创建套接字与IPEndPoint绑定,并设置为侦听模式。
其中注释掉的部分是利用Socket来创建侦听,这里我们可以看到用套接字助手类只通过二行就可以建立起侦听,而且如果要更方便一些,可以不指定IPEndPoint,单单指定端口就可以了,如:
2、侦听并获取接入的客户Socket连接
在这里用clientTcp = serverTcp.AcceptTcpClient();来接收连接的TcpClient对象,我们了可以通过
来接收一个Socket对象,如果接收的是一个Socket对象,那么接下来的接收和发送信息跟上篇一样,如果接收的是TcpClient对象,那么我们来看一下如何来接收和发送信息:
3 、接收和发送信息
通过NetworkStream ns = s.GetStream();可以获取网络流对象,以此来发送和接收信息。
二、客户端连接
1、创建套接字并连接到服务器
2、接收服务器发送的信息
同服务端,通过ns = clientTcp.GetStream();获取网络流来读取服务端发过来的信息。
3、向服务端发送信息
一、服务端侦听模式
1、创建套接字与IPEndPoint绑定,并设置为侦听模式。
1//创建IPEndPoint实例
2 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 6001);
3 /*
4 //创建一个套接字
5 serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
6 //将所创建的套接字与IPEndPoint绑定
7 serverSocket.Bind(ipep);
8 //设置套接字为收听模式
9 serverSocket.Listen(10);
10 */
11 serverTcp = new TcpListener(ipep);
12 serverTcp.Start();
2 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 6001);
3 /*
4 //创建一个套接字
5 serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
6 //将所创建的套接字与IPEndPoint绑定
7 serverSocket.Bind(ipep);
8 //设置套接字为收听模式
9 serverSocket.Listen(10);
10 */
11 serverTcp = new TcpListener(ipep);
12 serverTcp.Start();
其中注释掉的部分是利用Socket来创建侦听,这里我们可以看到用套接字助手类只通过二行就可以建立起侦听,而且如果要更方便一些,可以不指定IPEndPoint,单单指定端口就可以了,如:
1serverTcp = new TcpListener(6001);
2 serverTcp.Start();
2 serverTcp.Start();
2、侦听并获取接入的客户Socket连接
1while (true)
2 {
3 try
4 {
5 //在套接字上接收接入的连接
6 //clientSocket = serverSocket.Accept();
7 clientTcp = serverTcp.AcceptTcpClient();
8 clientThread = new Thread(new ThreadStart(ReceiveData));
9 clientThread.Start();
10 }
11 catch (Exception ex)
12 {
13 MessageBox.Show("listening Error: " + ex.Message);
14 }
15 }
2 {
3 try
4 {
5 //在套接字上接收接入的连接
6 //clientSocket = serverSocket.Accept();
7 clientTcp = serverTcp.AcceptTcpClient();
8 clientThread = new Thread(new ThreadStart(ReceiveData));
9 clientThread.Start();
10 }
11 catch (Exception ex)
12 {
13 MessageBox.Show("listening Error: " + ex.Message);
14 }
15 }
在这里用clientTcp = serverTcp.AcceptTcpClient();来接收连接的TcpClient对象,我们了可以通过
1clientSocket = serverTcp.AcceptSocket();
来接收一个Socket对象,如果接收的是一个Socket对象,那么接下来的接收和发送信息跟上篇一样,如果接收的是TcpClient对象,那么我们来看一下如何来接收和发送信息:
3 、接收和发送信息
1private void ReceiveData()
2 {
3 bool keepalive = true;
4 TcpClient s = clientTcp;
5 NetworkStream ns = s.GetStream();
6 Byte[] buffer = new Byte[1024];
7
8 //根据收听到的客户端套接字向客户端发送信息
9 IPEndPoint clientep = (IPEndPoint)s.Client.RemoteEndPoint;
10 lstServer.Items.Add("Client:" + clientep.Address + "("+clientep.Port+")");
11 string welcome = "Welcome to my test sever ";
12 byte[] data = new byte[1024];
13 data = Encoding.ASCII.GetBytes(welcome);
14 //s.Send(data, data.Length, SocketFlags.None);
15 ns.Write(data,0, data.Length);
16
17 while (keepalive)
18 {
19 //在套接字上接收客户端发送的信息
20 int bufLen = 0;
21 try
22 {
23 bufLen = s.Available;
24 //s.Receive(buffer, 0, bufLen, SocketFlags.None);
25 ns.Read(buffer, 0, bufLen);
26 if (bufLen == 0)
27 continue;
28 }
29 catch (Exception ex)
30 {
31 MessageBox.Show("Receive Error:" + ex.Message);
32 return;
33 }
34 clientep = (IPEndPoint)s.Client.RemoteEndPoint;
35 string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0, bufLen);
36
37 lstServer.Items.Add(clientcommand + "("+clientep.Address + ":"+clientep.Port+")");
38
39 }
40
41 }
2 {
3 bool keepalive = true;
4 TcpClient s = clientTcp;
5 NetworkStream ns = s.GetStream();
6 Byte[] buffer = new Byte[1024];
7
8 //根据收听到的客户端套接字向客户端发送信息
9 IPEndPoint clientep = (IPEndPoint)s.Client.RemoteEndPoint;
10 lstServer.Items.Add("Client:" + clientep.Address + "("+clientep.Port+")");
11 string welcome = "Welcome to my test sever ";
12 byte[] data = new byte[1024];
13 data = Encoding.ASCII.GetBytes(welcome);
14 //s.Send(data, data.Length, SocketFlags.None);
15 ns.Write(data,0, data.Length);
16
17 while (keepalive)
18 {
19 //在套接字上接收客户端发送的信息
20 int bufLen = 0;
21 try
22 {
23 bufLen = s.Available;
24 //s.Receive(buffer, 0, bufLen, SocketFlags.None);
25 ns.Read(buffer, 0, bufLen);
26 if (bufLen == 0)
27 continue;
28 }
29 catch (Exception ex)
30 {
31 MessageBox.Show("Receive Error:" + ex.Message);
32 return;
33 }
34 clientep = (IPEndPoint)s.Client.RemoteEndPoint;
35 string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0, bufLen);
36
37 lstServer.Items.Add(clientcommand + "("+clientep.Address + ":"+clientep.Port+")");
38
39 }
40
41 }
通过NetworkStream ns = s.GetStream();可以获取网络流对象,以此来发送和接收信息。
二、客户端连接
1、创建套接字并连接到服务器
1 //创建一个套接字
2 IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6001);
3 //clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4 clientTcp = new TcpClient();
5
6 //将套接字与远程服务器地址相连
7 try
8 {
9 //clientSocket.Connect(ipep);
10 clientTcp.Connect(ipep);
11 }
12 catch (SocketException ex)
13 {
14 MessageBox.Show("connect error: " + ex.Message);
15 return;
16 }
2 IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6001);
3 //clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4 clientTcp = new TcpClient();
5
6 //将套接字与远程服务器地址相连
7 try
8 {
9 //clientSocket.Connect(ipep);
10 clientTcp.Connect(ipep);
11 }
12 catch (SocketException ex)
13 {
14 MessageBox.Show("connect error: " + ex.Message);
15 return;
16 }
2、接收服务器发送的信息
1ns = clientTcp.GetStream();
2 while (true)
3 {
4 //接收服务器信息
5 int bufLen = 0;
6 try
7 {
8 //bufLen = clientSocket.Available;
9 bufLen = clientTcp.Available;
10
11 //clientSocket.Receive(data, 0, bufLen, SocketFlags.None);
12 ns.Read(data, 0, bufLen);
13 if (bufLen == 0)
14 {
15 continue;
16 }
17 }
18 catch (Exception ex)
19 {
20 MessageBox.Show("Receive Error:" + ex.Message);
21 return;
22 }
23
24 string clientcommand = System.Text.Encoding.ASCII.GetString(data).Substring(0, bufLen);
25
26 lstClient.Items.Add(clientcommand);
27
28 }
2 while (true)
3 {
4 //接收服务器信息
5 int bufLen = 0;
6 try
7 {
8 //bufLen = clientSocket.Available;
9 bufLen = clientTcp.Available;
10
11 //clientSocket.Receive(data, 0, bufLen, SocketFlags.None);
12 ns.Read(data, 0, bufLen);
13 if (bufLen == 0)
14 {
15 continue;
16 }
17 }
18 catch (Exception ex)
19 {
20 MessageBox.Show("Receive Error:" + ex.Message);
21 return;
22 }
23
24 string clientcommand = System.Text.Encoding.ASCII.GetString(data).Substring(0, bufLen);
25
26 lstClient.Items.Add(clientcommand);
27
28 }
同服务端,通过ns = clientTcp.GetStream();获取网络流来读取服务端发过来的信息。
3、向服务端发送信息
1//向服务器发送信息
2
3 byte[] data = new byte[1024];
4 data = Encoding.ASCII.GetBytes(txtClient.Text);
5 //clientSocket.Send(data, data.Length, SocketFlags.None);
6 ns.Write(data, 0, data.Length);
2
3 byte[] data = new byte[1024];
4 data = Encoding.ASCII.GetBytes(txtClient.Text);
5 //clientSocket.Send(data, data.Length, SocketFlags.None);
6 ns.Write(data, 0, data.Length);
到这里,我们就可以实现客户端与服务端的连接和通讯了。一些方法跟上一篇提到的类似,这里就不再详述。
接下来,我会讲一下关于Socket发送的消息边界处理问题、发送实体类数据问题以及利用线程池来改善线程创建和分配问题。