所以我试图在Visual Studio中使用.net套接字设置TCP服务器/客户端。到目前为止,它一直正常,直到客户端关闭应用程序。
错误似乎在这里。但是,我不确定在连接强行关闭后如何停止运行while循环。
while(true)
{
string theString = streamReader.ReadLine();
Console.WriteLine("Message recieved by client:" + theString);
}
//服务器代码//
static TcpListener tcpListener = new TcpListener(25000);
static void Listeners()
{
Socket socketForClient = tcpListener.AcceptSocket();
NetworkStream networkStream;
System.IO.StreamWriter streamWriter;
System.IO.StreamReader streamReader;
if (socketForClient.Connected)
{
Console.WriteLine("Client:" + socketForClient.RemoteEndPoint + " now connected to server.");
networkStream = new NetworkStream(socketForClient);
streamWriter = new StreamWriter(networkStream);
streamReader = new StreamReader(networkStream);
while(true)
{
string theString = streamReader.ReadLine();
Console.WriteLine("Message recieved by client:" + theString);
}
}
}
答案 0 :(得分:0)
你试过吗?
private bool IsConnected(Socket socketForClient)
{
get {return !(Socket.Poll(1, SelectMode.SelectRead)
&& socketForClient.Available ==0)}
}
...
while(IsConnected())
{
string theString = streamReader.ReadLine();
Console.WriteLine("Message recieved by client:" + theString);
// Do Stuff
}