Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# TcpClient-如何正确连接、维护连接并最终断开连接_C#_Tcpclient - Fatal编程技术网

C# TcpClient-如何正确连接、维护连接并最终断开连接

C# TcpClient-如何正确连接、维护连接并最终断开连接,c#,tcpclient,C#,Tcpclient,我有以下几种方法: private void connectToServer() { client = new TcpClient(SERVER_IP, PORT_NO); nwStream = client.GetStream(); writer = new StreamWriter(client.GetStream()); writer.AutoFlush = true; connected = tru

我有以下几种方法:

    private void connectToServer() {
        client = new TcpClient(SERVER_IP, PORT_NO);
        nwStream = client.GetStream();

        writer = new StreamWriter(client.GetStream());
        writer.AutoFlush = true;
        connected = true;

        getDataFromServer();
        rtb_inputField.Select();

        if (getDataTimer == null) {
            getDataTimer = new System.Timers.Timer();
            getDataTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            getDataTimer.Interval = 1000;
            getDataTimer.Enabled = true;
        }
    }

    private void disconnectFromServer() {
        if (connected) {
            writer.WriteLine("quit");
            getDataTimer.Enabled = false;
            getDataTimer.Dispose();
            getDataTimer = null;

            Thread.Sleep(1000);     //Wait 1 second
            nwStream.Close();
            client.Close();
            rtb_outputWindow.AppendText("\n\nClient: Disconnected.");
        }
        connected = false;
    }

    private void getDataFromServer() {
        if (connected) {
            new Thread(() => {
                Thread.CurrentThread.IsBackground = true;
                byte[] bytesToRead = new byte[client.ReceiveBufferSize];
                int readData = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
                updateOutputWindow(Encoding.Default.GetString(bytesToRead, 0, readData));
            }).Start();
        }
    }

    private void updateOutputWindow(string text) {
        string newText = string.Empty;

        if (InvokeRequired) {
            Invoke(new MethodInvoker(delegate () {
                updateOutputWindow(text);
            }));
        }
        else {
            newText = startRTFString;
            newText += rtb_outputWindow.Rtf;
            newText += replaceAnsiColorCodes(text);

            rtb_outputWindow.Rtf = newText;
        }
    }

    private void OnTimedEvent(object source, ElapsedEventArgs e) {
        if (connected) {
            getDataFromServer();
        }
    }
这一切都是可行的,但有些地方出了问题。当我断开outputWindow的连接时,在最后说“Client:Disconnected”之前会有很多新行。我与服务器的连接时间越长,断开连接的时间就越长

我相信计时器与这个问题有关。计时器的任务是不断地从服务器请求数据,并在收到任何数据时输出数据。有更好的方法吗?也许是“等待服务器发送数据”——如果在几秒钟内什么也没有发送,我就不必在服务器上敲打请求了


垃圾收集器是否负责getDataFromServer方法中的新线程?还是我需要以某种方式处理它?(这样我就不会创建一大堆后台线程。)

您不需要计时器来侦听传入的数据。这将自动为您处理。每次调用侦听线程任务时,它都应该获取任何传入数据,然后完成任务,以便其他线程可以执行

这里我有一个来自我的一个项目的听力任务示例。传入的数据是序列化的字符串

void ListeningObjectTask()// Recieves any data sent by the other user.
        {
            while (client != null && client.Connected)// If there is another user and they are connected.
            {
                try// This suppresses exceptions thrown by connection problems, such as the user losing network signal.
                {
                    recieve = str.ReadLine();// Gets the data sent by the other user.
                    if (recieve != "")// If the user has sent data.
                    {
                        lock (recievedStrings)// Locks the buffer to add the data sent by the other user to it.
                        {
                            recievedStrings.Enqueue(recieve);
                        }
                        recieve = "";// Clears the incoming data, as it has been stored.
                    }
                }
                catch (Exception Ex)
                {
                    // Ends all the other multiplayer objects as the connection has ended and they are no longer needed.
                    Disconnect();
                    // Tells the user why they have lost connection, so that they can try to fix the problem.
                    MessageBox.Show("Network connection ended\n" + Ex);
                }
            }
        }
以下是所用对象的声明:

private TcpClient client;// Allows connections for tcp network services.
private StreamReader str; // Provides an interface to read from a stream.
private string recieve;// The incoming string recieved from the other user.
readonly Queue<string> recievedStrings = new Queue<string>();// A buffer to hold incoming data from the other user.
专用TcpClient客户端;//允许连接tcp网络服务。
私有StreamReader str;//提供从流中读取的接口。
私有字符串接收;//从其他用户接收的传入字符串。
只读队列接收字符串=新队列();//用于保存来自其他用户的传入数据的缓冲区。

您不需要定时器来监听传入数据。这将自动为您处理。每次调用侦听线程任务时,它都应该获取任何传入数据,然后完成任务,以便其他线程可以执行

这里我有一个来自我的一个项目的听力任务示例。传入的数据是序列化的字符串

void ListeningObjectTask()// Recieves any data sent by the other user.
        {
            while (client != null && client.Connected)// If there is another user and they are connected.
            {
                try// This suppresses exceptions thrown by connection problems, such as the user losing network signal.
                {
                    recieve = str.ReadLine();// Gets the data sent by the other user.
                    if (recieve != "")// If the user has sent data.
                    {
                        lock (recievedStrings)// Locks the buffer to add the data sent by the other user to it.
                        {
                            recievedStrings.Enqueue(recieve);
                        }
                        recieve = "";// Clears the incoming data, as it has been stored.
                    }
                }
                catch (Exception Ex)
                {
                    // Ends all the other multiplayer objects as the connection has ended and they are no longer needed.
                    Disconnect();
                    // Tells the user why they have lost connection, so that they can try to fix the problem.
                    MessageBox.Show("Network connection ended\n" + Ex);
                }
            }
        }
以下是所用对象的声明:

private TcpClient client;// Allows connections for tcp network services.
private StreamReader str; // Provides an interface to read from a stream.
private string recieve;// The incoming string recieved from the other user.
readonly Queue<string> recievedStrings = new Queue<string>();// A buffer to hold incoming data from the other user.
专用TcpClient客户端;//允许连接tcp网络服务。
私有StreamReader str;//提供从流中读取的接口。
私有字符串接收;//从其他用户接收的传入字符串。
只读队列接收字符串=新队列();//用于保存来自其他用户的传入数据的缓冲区。

如何将所有这些连接到我当前拥有的内容?我需要一个TCPListener吗?这不是我发布关于c#sockets教程的地方。如果你有一个非常具体的问题,你可以给我发电子邮件(在我的个人资料页面上)。我如何将所有这些连接到我目前拥有的?我需要一个TCPListener吗?这不是我发布关于c#sockets教程的地方。如果你有一个非常具体的问题,你可以给我发电子邮件(在我的个人资料页面上)