我有一個快速和骯髒的問題。因此,我有兩個客戶端和一個服務器運行。我可以毫無問題地將來自客戶端的消息傳達給服務器。當我想從客戶端讀取兩條消息時出現問題 - 而不僅僅是一條消息。發送服務器多條消息? C#
我收到的錯誤是:IOException未處理。無法從傳輸連接讀取數據:現有連接被遠程主機強制關閉。
這是我在服務器端代碼:
私有靜態無效HandleClientComm(對象客戶端) { /**創建包含DatabaseFile對象**/ 名單theDatabase =新名單()的列表;
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」,它是由服務器就好了好評。只有當我試圖發送名爲「文本」的字符串時,問題纔會出現!
任何幫助將不勝感激 - 我不是那麼熟悉的插座,因此,我一直在試圖與現在明白這一點了一段
你能給我們多一點服務器端代碼嗎? –
另外,你可以發佈哪一行代碼拋出異常? – wllmsaccnt
沒有任何跡象表明你在'OptionOneInsert'之後向服務器發送任何東西 - 你沒有使用* clientStream2'。 –