发送服务器多条消息? C# [英] Send server multiple messages? C#
问题描述
我有一个快速和肮脏的问题。因此,我有两个客户端和一个服务器运行。我可以从客户端到服务器的消息,没有任何问题。我的问题出现时,我想从客户端读取两个消息,而不只是一个消息。
I have a quick and dirty question. So as it stands, i have two clients and a server running. I can communicate messages from the clients to the server without any problem. my problem appears when i want to read two messages from the client - rather than just one message.
我收到的错误是:IOException未处理。无法从传输连接读取数据:远程主机强制关闭了现有连接。
The error which i receive is: IOException was unhandled. Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
这是我的代码在服务器端:
Here is my code on the server side:
private static void HandleClientComm(object client)
{
/ **创建一个包含DatabaseFile对象的列表** /
List theDatabase = new List();
private static void HandleClientComm(object client) { /** creating a list which contains DatabaseFile objects **/ List theDatabase = new List();
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
do
{
bytesRead = 0;
try
{
// Blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception)
{
// A socket error has occured
break;
}
if (bytesRead == 0)
{
// The client has disconnected from the server
break;
}
// Message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("To: " + tcpClient.Client.LocalEndPoint);
Console.WriteLine("From: " + tcpClient.Client.RemoteEndPoint);
Console.WriteLine(encoder.GetString(message, 0, bytesRead));
if (encoder.GetString(message, 0, bytesRead) == "OptionOneInsert")
{
byte[] message2 = new byte[4096];
int bytesRead2 = 0;
**bytesRead2 = clientStream.Read(message, 0, 4096);** //ERROR occurs here!
Console.WriteLine("Attempting to go inside insert)");
Menu.Insert(theDatabase, bytesRead2);
}
这是我的客户代码:
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("OptionOneInsert");
Console.ReadLine();
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
NetworkStream clientStream2 = client.GetStream();
String text = System.IO.File.ReadAllText("FirstNames.txt");
clientStream2.Write(buffer, 0, buffer.Length);
clientStream2.Flush();
ASCIIEncoding encoder2 = new ASCIIEncoding();
byte[] buffer2 = encoder2.GetBytes(text);
Console.WriteLine("buffer is filled with content");
Console.ReadLine();
当客户端发送消息optionOne时,服务器接收到它。只有当我试图发送一个名为文本的字符串,问题出现!
When the client sends the message "optionOne" it is received by the server just fine. It's only when i attempt to send the string called "text" that the issues appears!
任何帮助将非常感激 - 我不是所有熟悉的插座,
Any help would be greatly appreciated - I'm not all that familiar with Sockets, hence i've been struggling with trying to understand this for sometime now
推荐答案
你有一个大
避免的最简单的方法是每个消息前缀与其中的字节数,例如作为固定的四字节格式。因此,要发送消息,您将:
The simplest way of avoiding that is to prefix each message with the number of bytes in it, e.g. as a fixed four-byte format. So to send a message you would:
- 将其从字符串编码为字节(理想情况下使用UTF-8,确保您将从不需要任何非ASCII文本)
- 将字节数组的长度写为四字节值
- 写出内容
- Encoding it from a string to bytes (ideally using UTF-8 instead of ASCII unless you're sure you'll never need any non-ASCII text)
- Write out the length of the byte array as a four-byte value
- Write out the content
在服务器上:
- 读取四个字节(如有必要,循环) -
- 将四个字节整数
- 分配该大小的字节数组
- 循环,从当前位置读取到缓冲区结尾,直到
- Read four bytes (looping if necessary - there's no guarantee you'd even read those four bytes together, although you almost certainly will)
- Convert the four bytes into an integer
- Allocate a byte array of that size
- Loop round, reading from "the current position" to the end of the buffer until you've filled the buffer
- Convert the buffer into a string
另一种替代方法是简单地将缓冲区转换为字符串使用 BinaryReader
和 BinaryWriter
- ReadString
和<$ c
Another alternative is simply to use BinaryReader
and BinaryWriter
- the ReadString
and WriteString
use length-prefixing, admittedly in a slightly different form.
使用长度加前缀是有分隔符(例如回车),但这意味着如果您需要在文本中包含分隔符以传输,则需要添加转义。
Another alternative you could use is to have a delimiter (e.g. carriage-return) but that means you'll need to add escaping in if you ever need to include the delimiter in the text to transmit.
这篇关于发送服务器多条消息? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!