-1

这是我将其放在按钮单击事件下的服务器代码。在与一个客户端发送数据并重新启动或刷新并与下一个客户端连接后,我该怎么办?

string val;
Process[] pname = Process.GetProcessesByName("chrome");
if (pname.Length == 0)
{
    MessageBox.Show("Application is not running");
    val = "Not Running";
}
else
{
    MessageBox.Show("Application is running");
    val = " Running";
}
TcpListener tcpListener = new TcpListener(10);
tcpListener.Start();
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
    label1.Show();
    label1.Text="Client connected";
    //MessageBox.Show("Client connected");
    NetworkStream networkStream = new NetworkStream(socketForClient);
    System.IO.StreamWriter streamWriter =
        new System.IO.StreamWriter(networkStream);
    System.IO.StreamReader streamReader =
        new System.IO.StreamReader(networkStream);
    string data_var;
    data_var = textBox1.Text;
    string theString =val;
    streamWriter.WriteLine(theString);
    try
    {
        streamWriter.Flush();
        theString = streamReader.ReadLine();
        label1.Text = theString;
        //MessageBox.Show(theString);
        streamReader.Close();
        networkStream.Close();
        streamWriter.Close();
    }
    catch
    {
        label1.Text = "Not flushed";
    }
}
try
{
    socketForClient.Close();
    //MessageBox.Show("Exiting...");
    label1.Text = "EXIT";
    Application.Restart();
}
catch 
{ }
4

1 回答 1

1

按照推荐的过程使用回调函数处理客户端,如这篇文章 http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server中所示

于 2012-10-12T07:57:40.473 回答