1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Net;
8 using System.Net.Sockets;
9 using System.Text;
10 using System.Threading;
11 using System.Threading.Tasks;
12 using System.Windows.Forms;
13
14 namespace socket服务
15 {
16 public partial class socket服务端 : Form
17 {
18 public socket服务端()
19 {
20 InitializeComponent();
21 Form.CheckForIllegalCrossThreadCalls = false;
22 }
23
24 private void Form1_Load(object sender, EventArgs e)
25 {
26
27 }
28 /// 创建一个字典,用来存储记录服务器与客户端之间的连接(线程问题)
29 private Dictionary<string, Socket> clientList = new Dictionary<string, Socket>();
30 /// <summary>
31 /// 启动服务
32 /// </summary>
33 /// <param name="sender"></param>
34 /// <param name="e"></param>
35 private void button1_Click(object sender, EventArgs e)
36 {
37 Thread myServer = new Thread(MySocket);
38 //设置这个线程是后台线程
39 myServer.IsBackground = true;
40 myServer.Start();
41 }
42 /// 创建连接的方法
43 private void MySocket()
44 {
45 try
46 {
47 //启用按钮不可用
48 button1.Enabled = false;
49 int port = 8201;
50 string host = "127.0.0.1";
51 IPAddress ip = IPAddress.Parse(host);
52 IPEndPoint ipe = new IPEndPoint(ip, port);
53 Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
54 sSocket.Bind(ipe);
55 sSocket.Listen(0);
56 listBox1.Items.Add("监听已经打开,请等待");
57 while (true)
58 {
59 Socket connectClient = sSocket.Accept();
60 if (connectClient != null)
61 {
62 string infor = connectClient.RemoteEndPoint.ToString();
63 clientList.Add(infor, connectClient);
64 listBox1.Items.Add(infor + "客户端接入!");
65 ///服务器将消息发送至客服端
66 string msg = "连接成功!";
67 SendMsg(msg);
68 //每有一个客户端接入时,需要有一个线程进行服务
69 Thread threadClient = new Thread(ReciveMsg);
70 threadClient.IsBackground = true;
71
72 //创建的新的对应的Socket和客户端Socket进行通信
73 threadClient.Start(connectClient);
74 }
75 }
76 }
77 catch (Exception ex)
78 {
79 button1.Enabled = true;
80
81 listBox1.Invoke(new MethodInvoker(delegate () { listBox1.Items.Add("发生异常:" + ex.Message); }));
82 }
83 }
84 /// 服务器接收到客户端发送的消息
85 private void ReciveMsg(object o)
86 {
87 //connectClient负责客户端的通信
88 Socket connectClient = o as Socket;
89 IPEndPoint endPoint = null;
90 while (true)
91 {
92 try
93 {
94 byte[] arrMsg = new byte[1024 * 1024];
95 int length = connectClient.Receive(arrMsg);
96 if (length > 0)
97 {
98 string recMsg = Encoding.UTF8.GetString(arrMsg, 0, length);
99 endPoint = connectClient.RemoteEndPoint as IPEndPoint;
100 //服务器显示客户端的端口号和消息
101 listBox1.Items.Add(DateTime.Now + "客户端请求:[" + endPoint.Port.ToString() + "]:" + recMsg);
102
103 //服务器(connectClient)发送接收到的客户端信息给客户端
104 SendMsg("服务端响应:[" + endPoint.Port.ToString() + "]:" + recMsg);
105 }
106 }
107 catch (Exception)
108 {
109 ///移除添加在字典中的服务器和客户端之间的线程
110
111 clientList.Remove(endPoint.ToString());
112 connectClient.Dispose();
113 listBox1.Items.Add("客户端连接断开!");
114 break;
115 }
116 }
117 }
118
119 /// 服务器发送消息,客户端接收
120 private void SendMsg(string str)
121 {
122 ///遍历出字典中的所有线程
123 foreach (var item in clientList)
124 {
125 byte[] arrMsg = Encoding.UTF8.GetBytes(str);
126 ///获取键值(服务器),发送消息
127 item.Value.Send(arrMsg);
128 }
129 }
130 /// <summary>
131 /// 窗体
132 /// </summary>
133 /// <param name="sender"></param>
134 /// <param name="e"></param>
135 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
136 {
137 listBox1.HorizontalScrollbar = true;//任何时候都显示水平滚动条
138 listBox1.ScrollAlwaysVisible = true;//任何时候都显示垂直滚动条
139 }
140 }
141 }