我有一个服务器和2个winform客户端(用于tictactoegame)。我可以立即检测到客户端断开连接吗?首先打开的客户端是player1套接字,第二个是player2。一旦两个客户端连接,player1必须单击一个按钮,并且播放器2按钮全部被禁用。在player1点击一个按钮后,播放器2按钮被启用,播放器1按钮被禁用...等等
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();
}
}
答案 0 :(得分:0)
关闭的播放器应该在退出之前正常关闭套接字。这涉及调用Socket.Shutdown(SocketShutdown.Send)
,然后等待接收操作返回0的字节计数(表示远程客户端也已关闭)。
这将确保及时关闭连接。否则,其他未关闭的玩家将无法知道连接是否已丢失,直到他们尝试发送一些数据为止。