简体   繁体   English

C#Socket编程,关闭窗口

[英]C# Socket programming, closing windows

So, I am writing this school project that should be some basic chat program that consists of a client and a server. 所以,我正在写这个学校项目,应该是一个由客户端和服务器组成的基本聊天程序。 I am trying to handle either the server or the client programs being closed. 我正在尝试处理服务器或正在关闭的客户端程序。

So when you press the big red X in the Client window, this is what happens: 因此,当您在客户端窗口中按下大红色X时,会发生以下情况:

private void Window_Closing(object sender, CancelEventArgs e)
{
    Data msgToSend = new Data();
    msgToSend.cmdCommand = Command.Logout; 
    msgToSend.strName = LoginName;
    byte[] b = msgToSend.ToByte();
    ClientSocket.Send(b);
}

It sends a message to the server informing it that someone is logging out, so it can remove the user from the user list, etc. 它向服务器发送一条消息,通知它有人正在注销,因此它可以从用户列表中删除用户等。

The problem occurs when the server is being closed, and it tries to send a message to the clients informing them that the server has shut down, so the clients can inform the users and then close. 服务器关闭时会出现问题,它会尝试向客户端发送消息,通知他们服务器已关闭,因此客户端可以通知用户然后关闭。

So the server's message arrives, and the client program is about to close, but the code above will try to inform the server falsely about the logout, but the server is already down by this time, so there will be a whole lot of error messages. 所以服务器的消息到了,客户端程序即将关闭,但上面的代码会尝试错误地通知服务器注销,但服务器此时已经关闭,所以会有很多错误消息。

I guess I would need some kind of an 'if' statement in the procedure above which could decide whether the code should run, but I have no idea what it should be. 我想在上面的过程中我需要某种'if'语句,它可以决定代码是否应该运行,但我不知道它应该是什么。 Ideas? 想法?

Simply check if the client is connected to the server. 只需检查客户端是否已连接到服务器。 Both Socket and TcpClient classes have a Connected property: SocketTcpClient类都具有Connected属性:

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected%28v=vs.110%29.aspx http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.connected(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected%28v=vs.110%29.aspx http://msdn.microsoft.com/en-us/library /system.net.sockets.tcpclient.connected(v=vs.110).aspx

You can then do: 然后你可以这样做:

 if (client.Connected) {
       Data msgToSend = new Data();
       msgToSend.cmdCommand = Command.Logout; 
       msgToSend.strName = LoginName;
       byte[] b = msgToSend.ToByte();
       ClientSocket.Send(b);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM