Re-opening a closed NetworkStream?
-
12-09-2019 - |
Question
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
Solution
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?
OTHER TIPS
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