我想使用C#
和套接字编程来创建一个简单的聊天程序。
问题是当我向服务器发送3条消息时,它不会单独读取它。
首先,它读取第一条消息,然后读取其余数据。
但是我想单独阅读所有消息。
例如,当我从客户端向服务器hello I'm Bill
发送3次时,我必须阅读3次或必须单独打印以显示屏幕。
但是它读了2次句子。如何分别打印所有消息?
这是我的客户Send
方法:
private void bSendMessage_Click(object sender, EventArgs e)
{
//this method sends to "hello i'm Bill" three times to the server.
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(rTBoxSendMessage.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
这是我的DoChat
方法,用于读取数据:
private void DoChat()
{
byte[] bytesFrom = new byte[8192];
string dataFromClient = null;
while (true)
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0,(int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
//Here is the problem
//it prints "hello i'm Bill" two times
//but i was sent three times
Console.WriteLine(dataFromClient);
Program.Broadcast(dataFromClient, clNo, true);
}
catch (Exception ex)
{
//Console.WriteLine("İstemci cikis yapti");
Console.WriteLine(ex.ToString());
clientSocket.Close();
break;
}
}
}