using System.Data;
using System.IO;
using System.Net.Sockets;
using System.Threading;
private Thread th;
private TcpListener tcpl;
private bool listenerRun = true;
private void Listen()
{
try
{
tcpl = new TcpListener(5656);
tcpl.Start();
statusBar1.Text = "正在监听...";
while(listenerRun)
{
Socket s = tcpl.AcceptSocket();
Byte[] stream = new Byte[80];
int i=s.Receive(stream) ;
string message = System.Text.Encoding.UTF8.GetString(stream);
richTextBox1.AppendText(message);
}
}
catch(System.Security.SecurityException)
{
MessageBox.Show("防火墙安全错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch(Exception)
{
statusBar1.Text = "已停止监听!";
}
}
private void Send()
{
try
{
string msg = "<"+textBox3.Text+">"+textBox2.Text;
TcpClient tcpc = new TcpClient(textBox1.Text, 5656);
NetworkStream tcpStream = tcpc.GetStream();
StreamWriter reqStreamW = new StreamWriter(tcpStream);
reqStreamW.Write(msg);
reqStreamW.Flush();
tcpStream.Close();
tcpc.Close();
richTextBox1.AppendText(msg);
textBox2.Clear();
}
catch(Exception)
{
statusBar1.Text = "目标计算机拒绝连接请求!";
}
}
private void Stop()
{
tcpl.Stop();
th.Abort();
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
th = new Thread(new ThreadStart(Listen));
th.Start();
}
private void button2_Click(object sender, System.EventArgs e)
{
button1.Enabled = true;
button2.Enabled = false;
listenerRun = false;
Stop();
}
private void button3_Click(object sender, System.EventArgs e)
{
Send();
}