我正在尝试学习服务器/客户端范例。我创建了一个服务器,用于侦听给定端口上的连接和输入。
我的问题是,当客户端连接并发送消息时,服务器会关闭连接,并停止侦听输入。我想要的是,当客户端发送消息时,服务器不应该关闭连接,但仍然继续从连接的客户端获取输入。我知道我一次只能处理一个客户端,因为我没有为每个客户端创建一个线程,但这不应该导致服务器在客户端发送消息后立即关闭连接。
这是我的服务器代码:
public void startServer() {
try {
IPAddress iAd = IPAddress.Parse("127.0.0.10");
TcpListener tcpListner = new TcpListener(iAd, 9000);
tcpListner.Start();
Console.WriteLine("The server is running on port: 9000");
Console.WriteLine("The local End point is: " + tcpListner.LocalEndpoint + "\nWaiting for a connection");
Socket socket = tcpListner.AcceptSocket();
Console.WriteLine("\nConnection from client: " + socket.RemoteEndPoint);
byte[] b =new byte[100];
int k = socket.Receive(b);
for (int i=0;i<k;i++) {
Console.Write("Recieved: " + Convert.ToChar(b[i]));
}
ASCIIEncoding asen=new ASCIIEncoding();
socket.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
socket.Close();
tcpListner.Stop();
} catch(Exception e) {
Console.WriteLine(e.Message);
}
}
客户端代码
public void StartClient(string servToConnectTo, int port) {
try{
client.Connect(servToConnectTo, port);
Console.WriteLine("Connected to server: " + servToConnectTo + " on port: " + port);
Console.WriteLine ("Write input to server...");
String input = Console.ReadLine();
Stream stream = client.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] b = asen.GetBytes(input);
Console.WriteLine("Sending...");
stream.Write(b, 0, b.Length);
byte[] bb = new byte[100];
int k = stream.Read(bb, 0, 100);
for(int i = 0; i < k; i++) {
Console.Write(Convert.ToChar(bb[i]));
}
client.Close();
} catch (Exception e) {
Console.WriteLine (e.Message);
}
}
我想我需要一个while loop
某个地方,但不知道在哪里