概述
首先是监听
namespace TcpIpTest
{
public partial class ListenerForm : Form
{
private Thread listenThread;
public bool keepReading=false;
public ListenerForm()
{
InitializeComponent();
}
private void actionButton_Click(object sender, EventArgs e)
{
if (!keepReading)
{
string address = IPAddressTextBox.Text;
string port = IPPortTextBox.Text;
string addressRegex = @"^d+.d+.d+.d+$";
string portRegx = @"^d+$";
if (Regex.IsMatch(address, addressRegex) && Regex.IsMatch(port, portRegx))
{
keepReading = true;
//监听的是本地的IP地址,因为电脑可以同时链接到多个网络,所以一台电脑可以同时有不同的IP地址,这里需要指明要监听哪个IP的哪个端口
listenThread = new Thread(() => ipListen(IPAddress.Parse(address), int.Parse(port)));
listenThread.Start();
this.stateLabel.Text = "正在监听";
this.actionButton.Text = "停止监听";
}
else
{
MessageBox.Show("请填写正确的IP地址和端口");
}
}
else
{
keepReading = false;
this.stateLabel.Text = "空闲";
this.actionButton.Text = "开始监听";
}
}
private void ipListen(IPAddress address, int port)
{
TcpListener listener = new TcpListener(address, port);
listener.Start();
OneString oneString = new OneString(changeResultTextBox);
while (keepReading)//这是一个阀,来控制是否脱离线程,因为要把listener停掉,所以不能用abort来关闭线程
{
if (listener.Pending())//这是判断是否有输入的,必须要加这个判断,不然线程就会在下面的AcceptTcpClient卡住
{
using (TcpClient client = listener.AcceptTcpClient())
{
//接收
NetworkStream netStream = client.GetStream();
byte[] receiveBytes = new byte[client.ReceiveBufferSize];
netStream.Read(receiveBytes, 0, client.ReceiveBufferSize);
string str = Encoding.Default.GetString(receiveBytes).TrimEnd('