我应该将 StreamReader/Writer 与 NetworkStream 一起用于 C# 服务器/客户端吗?
我正在为一个项目构建一个基于客户端/服务器的游戏(感觉非常超出我的深度)。我一直在使用 TCPclient 和多线程套接字服务器。目前一切工作正常,但我一直在使用 StreamReader 和 StreamWriter 在客户端和服务器之间进行通信。
我不断看到这样的例子用于接收数据:
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
和这个用于发送:
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
server.SendTo(data, iep);
我想知道使用它比streamReader 有什么好处?使用这个也会缓冲吗?
提前致谢。
I'm in the process of building a client/server based game for a project(feeling quite out my depth). I've been using TCPclient and a multi-threaded socket server. Everything is working fine at the moment but I have been using StreamReader and StreamWriter to communicate between both client and server.
I keep seeing examples like this for recieving data:
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
and this for sending:
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
server.SendTo(data, iep);
I was wondering what are the benefits of using this over streamReader? Would using this also be buffering?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这只是一种不同的风格。
ReceiveFrom
和SendTo
更偏向 Unix 风格,而使用StreamReader
则更偏向 .NET 风格。StreamReader
对您来说更有用,因为您可以将其传递给接受TextReader
的其他方法。It's just a different style.
ReceiveFrom
andSendTo
are more Unix-style, and using aStreamReader
is more of a .NET style.StreamReader
would be of more use to you, as you could then pass it to other methods that accept aTextReader
.sendTo()
和receiveFrom()
用于使用 UDP 作为传输协议的无连接套接字。当使用面向连接或使用 TCP 作为协议的流套接字时,您可以使用Send()
或Recieve()
。StreamReader 和 StreamWriter 是 IO 命名空间的类,有助于解决 TCP 套接字带来的消息边界问题。
消息边界问题意味着所有发送调用都不会在所有接收调用中被接听。
为了避免消息边界问题,我们使用带有流读取器和流写入器的网络流。
sendTo()
andreceiveFrom()
are used for connection less sockets, that use UDP as the transport protocol. You can useSend()
orRecieve()
when using connection oriented or stream sockets that use TCP as the protocol.StreamReader and StreamWriter are the classes of IO namespace that will help in solving the message boundary problem that come with TCP sockets.
Message boundary problem means that all send calls are not picked up in all receive calls.
To avoid the message boundary problem we use networkstream with streamreader and streamwriter.