using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SocketServer
{
public partial class Form1 : Form
{
private List<TcpClient> clientList=new List<TcpClient>();///保存客户连接socket
private TcpListener tcpListener;///监听类
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
tcpListener = new TcpListener(IPAddress.Any, );//监听3000端口
tcpListener.Start();//开始监听
Thread listenThread = new Thread(new ThreadStart(ListenForClients));///新建线程来处理新的客户端连接
listenThread.Start();
}
/// <summary>
/// 处理客户端连接线程
/// </summary>
private void ListenForClients()
{
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
clientList.Add(client);
listBox2.BeginInvoke(new Action(()=>{listBox2.Items.Add(client.Client.RemoteEndPoint.ToString());}));
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
/// <summary>
/// 读客户端数据
/// </summary>
/// <param name="client"></param>
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[];
int bytesRead;
while (true)
{
bytesRead = ;
try
{
//blocks until a client sends a message,每个线程在这一句时会中断一下,等待客户端有数据传进来后再往下执行
bytesRead = clientStream.Read(message, , );
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == )
{
//the client has disconnected from the server
break;
}
//message has successfully been received
UTF8Encoding utf8 = new UTF8Encoding();
System.Diagnostics.Debug.WriteLine(utf8.GetString(message, , bytesRead));
///线程里修改UI界面的内容要用invoke方法和委托
listBox1.Invoke(new Action(() => { listBox1.Items.Add(utf8.GetString(message, , bytesRead)); }));
}
//tcpClient.Close();//不要关闭
}
/// <summary>
/// 向所有客户端发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
foreach (var item in clientList)
{
NetworkStream stream=item.GetStream();
stream.Write(UTF8Encoding.UTF8.GetBytes(this.textBox1.Text), , UTF8Encoding.UTF8.GetBytes(this.textBox1.Text).Length);
}
}
}
}