public partial class Form1 : Form
{
private TcpListener server;
private Thread receive_thread;
public Form1()
{
InitializeComponent();
RichTextBox.CheckForIllegalCrossThreadCalls = false;
}
private void receive()
{
server = new TcpListener(IPAddress.Parse(textBox1.Text), Int32.Parse(textBox2.Text));
server.Start(); //启动监听
label8.Text = "正在监听......";
while (true)
{
TcpClient theClient = server.AcceptTcpClient(); //接收挂起的连接请求
NetworkStream theStream = theClient.GetStream();//取得接收数据的网络流
Byte[] messageByte = new byte[1024];
theStream.Read(messageByte, 0, messageByte.Length);
string readMessage = System.Text.Encoding.BigEndianUnicode.GetString(messageByte);
richTextBox1.AppendText(readMessage);
}
}
private void button1_Click(object sender, EventArgs e)
{
//判断IP地址和端口是否合法
try
{
IPAddress.Parse(textBox1.Text);
Int32.Parse(textBox2.Text);
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
return;
}
//如果监听线程已经在运行中,则返回
if (receive_thread != null && receive_thread.ThreadState == ThreadState.Running)
{
MessageBox.Show("正在监听中......");
return;
}
try
{
receive_thread = new Thread(new ThreadStart(receive));
receive_thread.Start();
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("请输入监听端IP地址,端口号请保持一致!\n发送端为自身IP");
string name = Dns.GetHostName();
IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
textBox3.Text = ipadrlist[2].ToString();
textBox1.Text = ipadrlist[2].ToString();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//如果监听线程扔在运行,则不能关闭
if (receive_thread != null && receive_thread.ThreadState == ThreadState.Running)
{
MessageBox.Show("请先停止监听再关闭本程序。");
e.Cancel = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
//判断IP地址和端口是否合法
try
{
IPAddress.Parse(textBox3.Text);
Int32.Parse(textBox4.Text);
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
return;
}
//如果没有启动监听,则返回
if (receive_thread == null || receive_thread.ThreadState != ThreadState.Running)
{
MessageBox.Show("请先启动监听。");
return;
}
//创建客户端并发送连接请求
TcpClient theClient = new TcpClient(textBox3.Text, Int32.Parse(textBox4.Text));
string send = richTextBox2.Text + "\r\n";
//转换编码格式
byte[] messageByte = System.Text.Encoding.BigEndianUnicode.GetBytes(send.ToCharArray());
NetworkStream theStream = theClient.GetStream(); //取得发送数据的网络流
theStream.Write(messageByte, 0, messageByte.Length);//写数据
theStream.Close(); //关闭流
theClient.Close(); //关闭客户端
}
private void button3_Click(object sender, EventArgs e)
{
//如果没有启动监听,则返回
if (receive_thread == null || receive_thread.ThreadState != ThreadState.Running)
{
MessageBox.Show("监听没有开始。");
return;
}
if (receive_thread != null && receive_thread.ThreadState == ThreadState.Running)
{
try
{
receive_thread.Abort();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
}
if (server != null)
{
server.Stop();
}
}
}