What is the difference between Socket.Send and Stream.Write? (in relation to tcp ip connections)

爷,独闯天下 提交于 2019-12-24 01:22:13

问题


In dealing with server/client connections, I have seen both of these used effectively without any apparent advantages to either, yet I doubt they would both exist if there weren't any known advantages to one or the other. Does anyone know any clear differences between the two? Help would be much appreciated, thanks.


回答1:


Socket.Send is a raw send of data directly through the WINSOCK layer... Stream buffers and processes data as you send it. It's generally used for situations where you need stream-like functionality. There's some extra overhead there, obviously. In comparison to Send, this overhead includes creating a new class to manage a "stream" and introducing a couple of layers of indirection between you and Socket.Send. NetworkStream.Write eventually just calls Socket.Send; but that's a couple of layers of overhead down.

There's also a bit more work to get the stream set up, through the use of the NetworkStream type.

If course, a stream can also be bidirectional, meaning you can both read and write to it. You can read from a socket perfectly fine with the Receive methods.

Use of Send or Receive directly couples you to socket. If you use a Stream-derivative, you're decoupled from Socket and free to use methods/classes that work with Stream.



来源:https://stackoverflow.com/questions/11636903/what-is-the-difference-between-socket-send-and-stream-write-in-relation-to-tcp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!