我正在开发一个作为服务器和客户端的程序。我想要做的是让客户端显示一条消息,告知它是否连接到服务器。我认为最好的方法是每隔一秒让客户发送一个" alive"消息然后让服务器响应。
当客户端向服务器发送一条消息时,它会显示它已连接一次,然后每次显示后它都没有连接。所以我知道客户端正在工作,因为报告没有连接,但服务器只响应一次然后停止。我的问题是服务器似乎只响应客户端一次。之后我根本得不到服务器的响应。
注意:在检查连接之前,会调用与服务器的连接。没想到它与问题有关
客户代码
public static void CheckServerConection(object Sender, EventArgs e)
{
try
{
NetworkStream nwStream = tcpClnt.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes("Alive");
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
byte[] bytesToRead = new byte[tcpClnt.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, tcpClnt.ReceiveBufferSize);
string received = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
if (received == "Alive")
{
ActiveConnection = true;
Console.WriteLine("Connected");
}
else
{
ActiveConnection = false;
Console.WriteLine("Not Connected");
}
}
catch (Exception exception)
{
ActiveConnection = false;
Console.WriteLine("Not Connected");
}
}
服务器代码
public static void startServer()
{
try
{
IPAddress ipAd = IPAddress.Parse("0.0.0.0"); //Servers local IP address.
int port = 36512;
TcpListener listener = new TcpListener(ipAd, port);
int i = 0;
while (i == 0)
{
listener.Start();
Console.WriteLine("Server has been started." + Environment.NewLine + "Running on: " + ipAd + ":" + port);
Console.WriteLine("Waiting for client connection...");
TcpClient client = listener.AcceptTcpClient();
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine(dataReceived);
nwStream.Write(buffer, 0, bytesRead);
listener.Stop();
client.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
答案 0 :(得分:1)
您正在循环外实现监听器。你在循环中调用了listener.Stop()方法,它关闭了监听器。之后,它无法重启。 请参阅此链接,以便在"示例"中正确,简单地实现TcpListener。部分。
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx