重新打开关闭的 NetworkStream?
早上好,
我需要一些建议,我正在使用一个网络流,它是从 TcpClient 流式传输的,一切都工作正常,但后来我需要其他地方的一些功能,这需要关闭流。我似乎无法找到关闭连接后重新打开连接的方法。有人能在这里指出正确的方向吗?
这是我所基于的代码的示例:(显然这并不完全是它的工作原理,但我已经尽可能地简化了它:-))
private void MyMainFunction()
{
ConnectToTcp();
if(CheckConnection == true)
{
DoWorkWithTcp();
}
DisconnectFromTcp();
ConnectViaOtherSource();
DoOtherSourceWork();
DisconnectOtherSource();
ConnectToTcp(); //Excecption thrown, epic fail!
}
private void ConnectToTcp()
{
myClient = new TcpClient(ip, port);
myNetStream = myClient.GetStream();
}
private void DisconnectFromTcp()
{
myNetStream.Close();
myClient.Close();
}
提前致谢,不胜感激。
编辑 - 更改了变量拼写名称!哎呀!
编辑 - 抱歉,刚刚意识到问题来自其他地方,感谢您确认此代码是正确的:-)帮助我从另一个来源发现问题
Good morning,
I am in need of some advice, I am using a networkStream, which is streaming from a TcpClient, all was working fine, but then I required the some functionality elsewhere, which requires the stream to be closed. I can't seem to find a way to re open the connection once it has been closed. Could anyone point me in the correct direction here?
Here's an example of the code I am based on: (Obviously this isn't exactly how it works, but I've simplified it as much as possible :-))
private void MyMainFunction()
{
ConnectToTcp();
if(CheckConnection == true)
{
DoWorkWithTcp();
}
DisconnectFromTcp();
ConnectViaOtherSource();
DoOtherSourceWork();
DisconnectOtherSource();
ConnectToTcp(); //Excecption thrown, epic fail!
}
private void ConnectToTcp()
{
myClient = new TcpClient(ip, port);
myNetStream = myClient.GetStream();
}
private void DisconnectFromTcp()
{
myNetStream.Close();
myClient.Close();
}
Thanks in advance, appreciated.
Edit - Changed variable spelling name! Whoops!
Edit - Sorry, just realised the problem was coming from elsewhere, thanks for confirming that this code is correct :-) Helped me spot the problem from another source
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题出现了,为什么您必须完全关闭连接,您不能在 DoOtherSourceWork() 期间保持连接打开(休眠)吗?
除此之外,代码看起来不错,创建了一个新的 TcpClient 等,所以我认为这取决于另一边 - 当您关闭连接时对等软件会做什么?
The question comes up why you have to close the connection at all, can't you keep it open (dormant) during DoOtherSourceWork() ?
Apart from that, the code looks OK, creating a new TcpClient etc, so I think it depends on the other side - what does the peer software do when you close the connection?
不确定,因为您没有粘贴整个内容,但
myClient = new TcpClient(ip, port);
myNetStream = sockClient.GetStream();
sockClient 不是 myClient 这是一个拼写错误还是它实际上在代码中?如果是这种情况,您还需要重新创建 sockClient
Not sure since you didnt paste the whole thing but
myClient = new TcpClient(ip, port);
myNetStream = sockClient.GetStream();
sockClient is not myClient is this a typo or its actually in the code? if thats the case you need to recreate sockClient aswell