c#检测客户端与服务器的断开连接
本文关键字:断开 连接 服务器 检测 客户端 | 更新日期: 2023-09-27 18:28:50
我有一台服务器和两个winform客户端(用于tictactoe游戏)。我能立即检测到客户端断开连接吗?。第一个打开的客户端是player1套接字,第二个是player2。一旦两个客户端都连接好,player1必须单击一个按钮,player2的按钮都将被禁用。在player1点击按钮后,player2按钮被启用,player1按钮被禁用。。。也是如此
isConnected方法
public bool IsConnected(Socket socket)
{
try
{
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}
catch (SocketException) { return false; }
}
服务器代码
public class ServerApp
{
public Socket serverSocket;
Socket player1;
Socket player2;
ServerGame myGame;
public ServerApp()
{
myGame = new ServerGame();
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8221);
serverSocket.Bind(ipLocal);
serverSocket.Listen(4);
Console.WriteLine("Waiting for clients ...");
player1 = serverSocket.Accept();
Console.WriteLine("Player 1 joined");
player2 = serverSocket.Accept();
Console.WriteLine("Player 2 joined");
myGame.InitGame();
while (true)
{
try
{
myGame.Display();
Console.WriteLine();
myGame.Send(player1, BaseGame.Player.One);
myGame.Send(player2, BaseGame.Player.Two);
if (myGame.GetActivePlayer() == BaseGame.Player.One &&
myGame.IsConnected(player1)==true)
{
myGame.Receive(player1);
}
else if(myGame.IsConnected(player1) == true)
{
myGame.Receive(player2);
}
}
catch(Exception e)
{
Console.WriteLine(e);
Thread.Sleep(1000);
}
}
Console.WriteLine("Server going down");
Thread.Sleep(2000);
}
}
class Program
{
static void Main(string[] args)
{
ServerApp serverApp = new ServerApp();
}
}
被关闭的播放器应该在退出之前优雅地关闭套接字。这包括调用Socket.Shutdown(SocketShutdown.Send)
,然后等待接收操作返回字节计数0(表示远程客户端也已关闭)。
这将确保及时关闭连接。否则,其他未被关闭的玩家将无法知道连接已丢失,直到他们尝试发送一些数据。