我正在嘗試使用c#進行客戶端服務器通信。我讓客戶端和服務器之間進行了通信。但是,我面臨的問題是如何停止溝通?使用c停止在客戶端服務器中的通信#
條件:服務器應該始終在監聽(當有多個客戶端時)。(目前,我正在使用單個客戶端)。客戶端應該有一個停止或退出條件(即;當客戶端發送「退出」時,客戶端應該終止,服務器應該仍然在監聽其他客戶端)。
我是新來的c#。嘗試搜索谷歌也。但沒有找到我所需要的。我的代碼
部分:
服務器:
try
{
IPAddress addr = IPAddress.Parse("127.0.0.1");
string a = "recieved by server";
TcpListener Receiver = new TcpListener(addr, 1234);
Receiver.Start();
Console.WriteLine("trying to connect to " + addr);
Socket s = Receiver.AcceptSocket();
Console.WriteLine("Connected");
while (true)
{
byte[] b = new byte[100];
int k = s.Receive(b);
char[] chars = new char[b.Length/sizeof(char)];
System.Buffer.BlockCopy(b, 0, chars, 0, b.Length);
string dataReceived = new string(chars);
Console.WriteLine(dataReceived);
byte[] bw = new byte[a.Length * sizeof(char)];
System.Buffer.BlockCopy(a.ToCharArray(), 0, bw, 0, bw.Length);
Console.WriteLine("sending Acknowledgement to client");
s.Send(bw);
}
//Receiver.Stop();
}
客戶:
try
{
TcpClient TcpC = new TcpClient();
TcpC.Connect("127.0.0.1", 1234);
while (true)
{
Console.WriteLine("enter somethiong to send");
String s = Console.ReadLine();
NetworkStream CStream = TcpC.GetStream();
byte[] bw = new byte[s.Length * sizeof(char)];
System.Buffer.BlockCopy(s.ToCharArray(), 0, bw, 0, bw.Length);
Console.WriteLine("Transmit");
CStream.Write(bw, 0, bw.Length);
if (s == "exit")
{
CStream.Flush();
CStream.Close();
TcpC.Close();
break;
}
byte[] br = new byte[100];
int k = CStream.Read(br, 0, 100);
char[] chars = new char[br.Length/sizeof(char)];
System.Buffer.BlockCopy(br, 0, chars, 0, br.Length);
string ackReceived = new string(chars);
Console.WriteLine(ackReceived);
}
//TcpC.Close();
}
改程序accoding什麼Ozmo的說。但是,我不知道線程。你能舉一個例子說明我如何改變我的程序? –