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 SocketServer
15 {
16 public partial class Form1 : Form
17 {
18 private List<TcpClient> clientList=new List<TcpClient>();///保存客户连接socket
19 private TcpListener tcpListener;///监听类
20
21 public Form1()
22 {
23 InitializeComponent();
24 }
25
26 private void button3_Click(object sender, EventArgs e)
27 {
28 tcpListener = new TcpListener(IPAddress.Any, 3000);//监听3000端口
29 tcpListener.Start();//开始监听
30 Thread listenThread = new Thread(new ThreadStart(ListenForClients));///新建线程来处理新的客户端连接
31 listenThread.Start();
32
33 }
34
35 /// <summary>
36 /// 处理客户端连接线程
37 /// </summary>
38 private void ListenForClients()
39 {
40 while (true)
41 {
42 //blocks until a client has connected to the server
43 TcpClient client = this.tcpListener.AcceptTcpClient();
44 clientList.Add(client);
45 listBox2.BeginInvoke(new Action(()=>{listBox2.Items.Add(client.Client.RemoteEndPoint.ToString());}));
46 //create a thread to handle communication
47 //with connected client
48 Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
49 clientThread.Start(client);
50
51 }
52 }
53
54 /// <summary>
55 /// 读客户端数据
56 /// </summary>
57 /// <param name="client"></param>
58 private void HandleClientComm(object client)
59 {
60 TcpClient tcpClient = (TcpClient)client;
61 NetworkStream clientStream = tcpClient.GetStream();
62 byte[] message = new byte[4096];
63 int bytesRead;
64 while (true)
65 {
66 bytesRead = 0;
67 try
68 {
69 //blocks until a client sends a message,每个线程在这一句时会中断一下,等待客户端有数据传进来后再往下执行
70 bytesRead = clientStream.Read(message, 0, 4096);
71 }
72 catch
73 {
74 //a socket error has occured
75 break;
76 }
77 if (bytesRead == 0)
78 {
79 //the client has disconnected from the server
80 break;
81 }
82
83 //message has successfully been received
84 UTF8Encoding utf8 = new UTF8Encoding();
85 System.Diagnostics.Debug.WriteLine(utf8.GetString(message, 0, bytesRead));
86 ///线程里修改UI界面的内容要用invoke方法和委托
87 listBox1.Invoke(new Action(() => { listBox1.Items.Add(utf8.GetString(message, 0, bytesRead)); }));
88 }
89
90 //tcpClient.Close();//不要关闭
91 }
92
93 /// <summary>
94 /// 向所有客户端发送
95 /// </summary>
96 /// <param name="sender"></param>
97 /// <param name="e"></param>
98 private void button4_Click(object sender, EventArgs e)
99 {
100 foreach (var item in clientList)
101 {
102 NetworkStream stream=item.GetStream();
103 stream.Write(UTF8Encoding.UTF8.GetBytes(this.textBox1.Text), 0, UTF8Encoding.UTF8.GetBytes(this.textBox1.Text).Length);
104 }
105 }
106 }
107 }