ic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.Net;
11 using System.Net.Sockets;
12 using System.Threading;
13
14 namespace DotnetSocketClient
15 {
16 public partial class DotnetSocketClient : Form
17 {
18 public DotnetSocketClient()
19 {
20 InitializeComponent();
21 }
22 byte[] buffer = new byte[2048];
23 Socket socket;
24 Thread thread;
25
26 /// <summary>
27 /// 连接服务器
28 /// </summary>
29 /// <param name="sender"></param>
30 /// <param name="e"></param>
31 private void btn_start_Click(object sender, EventArgs e)
32 {
33 try
34 {
35 //实例化socket
36 socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
37 //连接服务器
38 socket.Connect(new IPEndPoint(IPAddress.Parse(txt_ip.Text), int.Parse(txt_port.Text)));
39
40 thread = new Thread(StartReceive);
41 thread.IsBackground = true;
42 thread.Start(socket);
43 }
44 catch (Exception ex)
45 {
46 SetMessage("服务器异常:" + ex.Message);
47 }
48
49 }
50 /// <summary>
51 /// 开启接收
52 /// </summary>
53 /// <param name="obj"></param>
54 private void StartReceive(object obj)
55 {
56 string str;
57 while (true)
58 {
59 Socket receiveSocket = obj as Socket;
60 try
61 {
62 int result = receiveSocket.Receive(buffer);
63 if (result == 0)
64 {
65 break;
66 }
67 else
68 {
69 str = Encoding.Default.GetString(buffer);
70 SetMessage("接收到服务器数据: " + str);
71 }
72
73 }
74 catch (Exception ex)
75 {
76 SetMessage("服务器异常:" + ex.Message);
77
78 }
79 }
80
81 }
82 /// <summary>
83 /// 关闭连接
84 /// </summary>
85 /// <param name="sender"></param>
86 /// <param name="e"></param>
87 private void btn_close_Click(object sender, EventArgs e)
88 {
89 try
90 {
91 socket.Shutdown(SocketShutdown.Both);
92 socket.Close();
93 thread.Abort();
94 SetMessage("关闭与远程服务器的连接!");
95 }
96 catch (Exception ex)
97 {
98 SetMessage("异常" + ex.Message);
99 }
100 }
101
102 private void button1_Click(object sender, EventArgs e)
103 {
104 socket.Send(Encoding.Default.GetBytes(txt_send.Text));
105 txt_send.Clear();
106 }
107 /// <summary>
108 /// 添加信息
109 /// </summary>
110 /// <param name="msg"></param>
111 private void SetMessage(string msg)
112 {
113 richTextBox1.Invoke(new Action(() => { richTextBox1.AppendText(msg+"\r\n"); }));
114 }
115 }
116 }
View Code
接下来测试
因为我们在本地测试,所以使用回环地址为服务的监听地址(127.0.0.1),端口号范围(0~65535)但不能和正在使用的端口号冲突,所以尽量设置大一些的值,本次测试使用端口号 3333,
这里总结一个查看正在使用的端口号的方法:
win+R打开命令提示符,然后输入 netstat -a -n 回车,会列出当前正在使用的协议,内部地址,外部地址和状态
服务器端 输入ip ,输入端口,开启监听 ,客户端输入服务器ip和端口, 点击开始连接
客户端
可以看到,客户端点击连接以后服务器已收到客户端的连接,并作出提示,并且将来访客户端的ip和端口号记录
接下来测试 互相发送数据
服务器给客户端发送数据:
从客户端列选择对应客户端ip,然后从下边textbox 输入要发送的数据,点击发送
服务器:
客户端:
客户端给服务器发送数据:
从客户端的textbox中输入要发送的数据,点击发送
服务器:
客户端
一般情况下,都不会是服务器与客户端一对一的数据交互,接下来 我们借助上边推荐的工具,测试一下多个客户端访问服务器
首先在SocketTool上创建多个客户端,我们可以清楚的看到 |