110,534
社区成员
发帖
与我相关
我的任务
分享
delegate void addtxt(string str);
private void AddTxt(string str)
{
if (this.InvokeRequired)
{
this.Invoke(new addtxt(AddTxt), str);
}
else
{
textBox1.Text += str;
}
}
....
//textBox1.Text += "waiting for connection..."; 界面要用Invoke
//修改为->
AddTxt("waiting for connection...");
private const int portNum = 13;
TcpListener listener;
bool done = false;
private void Form1_Load(object sender, EventArgs e)
{
done = false;
IPAddress local = IPAddress.Parse("127.0.0.1");
listener = new TcpListener(local,portNum);
listener.Start();
Thread thread = new Thread(new ThreadStart(ListenThread));
thread.IsBackground = true;
thread.Start();
}
private void ListenThread()
{
while (!done)
{
//textBox1.Text += "waiting for connection..."; 界面要用Invoke
TcpClient client = listener.AcceptTcpClient();//在这一行就不动了。界面显示不了。也不抛出异常
//textBox1.Text += "Connection accepted\r\n";
NetworkStream ns= client.GetStream();
byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
try
{
ns.Write(byteTime, 0, byteTime.Length);
ns.Close();
client.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
listener.Stop();
}