如何在不导致错误的情况下关闭TcpClient连接? [英] How can I close a TcpClient connection without causing an error?

查看:107
本文介绍了如何在不导致错误的情况下关闭TcpClient连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用套接字使用visual basic 2010创建聊天模拟应用程序。我已设法使连接工作,并在我的应用程序的两个实例之间发送和接收数据。但当我关闭其中一个时,另一个开始收到最后收到的消息,并反复将其添加到消息文本框中,直到程序阻塞并停止工作。我尝试关闭表单上的连接,如下所示:

I'm using sockets to create a chat simulation application using visual basic 2010. I've managed to make the connection work and send and receive data between two instances of my app. But when I close one of them, the other one starts getting the last received message and adding it to the message textbox repeatedly until the program jams and stops working. I've tried closing the connection on form closing like so:

Private Sub ChatWindow_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If Mode = mode.Server Then
            ServerSocket.Stop()
        End If
        NetworkStream.Close()
        ClientSocket.Close()
    End Sub



我希望应用程序成为abl e作为服务器或作为客户端,所以我建立了一种通信模式(服务器或客户端,如果你作为服务器启动,你打开一个tcplistener),这似乎工作正常。只是当我想要注销或关闭两个应用程序中的一个时。当我研究所有我能找到的是我必须关闭网络流以及tcpclient,但我尝试了,我仍然有同样的问题。我怎么能避免这个?如何确定两个端点之一何时断开连接并在屏幕上显示一条消息,告诉另一端不再可用?另外,如何判断是否有可用于连接的客户端,因此作为服务器运行的实例在没有响应时不会冻结?


I want the application to be able to act as server or just as client, so I've established a communication mode (server or client, if you start as server you open a tcplistener) and that seems to be working fine. It's just when I want to "Log off" or just close one of the two apps. When I researched all I could find was that I had to close the network stream as well as the tcpclient, but I tried that and I still have the same problem. How can I avoid this? How can I tell when one of the two end points disconnects and just show a message on screen to tell that the other end is no longer available? Additionally, how can I tell if there's a client available for connection, so the instance running as a server doesn't freeze when it gets no response?

推荐答案

使用方法可能会解决此问题:



using methodology might resolve this issue as:

using (TcpClient tcpClient = new TcpClient())
{
   if (tcpClient != null)
   {
    tcpClient.GetStream().Close();
    tcpClient.Close();
    tcpClient = null;
   }
}


这篇关于如何在不导致错误的情况下关闭TcpClient连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆