I have a client-server application which communicates over TCP/IP.
I use System.Net.Sockets.Socket
type object for ascnyronous communication over TCP. Basicly i open connection send/receive data and close connection. And my implementation is based on Socket type objects.
Now i need to use a third-party dll to do something. This dll expects a System.IO.Stream
type object. So i need to get Stream object of my Socket object.
How can i do that?
Thank you.
Asked
Active
Viewed 2.8k times
12

Fer
- 1,962
- 7
- 29
- 58
-
4Be careful when mixing Socket and Stream - a socket instance is threadsafe - a stream instance is not! – weismat May 09 '12 at 15:35
2 Answers
20
Pretty simple really. The constructor for the NetworkStream class accepts a socket to wrap:
http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx
// NOTE: This demonstrates disposal of the stream when you are
// done with it- you may not want that behavior.
using (var myStream = new NetworkStream(mySocket)) {
my3rdPartyObject.Foo(myStream);
}

Chris Shain
- 50,833
- 6
- 93
- 125
-
5Just in case the user of that stream will want to call `myStream.Close()`, I recommend to construct the NetworkStream with ownership of the socket: `new NetworkStream(mySocket, true)`. Otherwise you end up wondering why the thread that blocks in a read operation is still blocked after closing the stream. – Stefan Bormann Jan 18 '18 at 08:24
1
Try looking at System.Net.Sockets.SocketType.Stream ?
Or try looking at the System.Net.Sockets.NetworkStream ?
http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx

John Smith
- 1,194
- 1
- 12
- 30