我用 Java 编写了一个客户端-服务器聊天室。我想确保所有用户都在线,如果有人断开连接,我想告诉大家他已经离开了。如何查看用户是否在线?我有一个包含这些数据的类:每个用户的用户名、套接字、ObjectInputStream、ObjectOutputStream ......非常感谢。
问问题
934 次
2 回答
0
您需要做的就是检查Socket
对象。假设在 TCP 连接实际进入之前没有构建每个用户的类,只需使用Socket#isClosed()
. 还要注意记录在getInputStream()
.
于 2013-08-17T16:16:10.847 回答
0
您可以使用它检查通过端口的流量。我不久前写的这个程序监视套接字。如果您将消息多播到各种套接字,您可以修改此程序以在该端口上提供客户端的存在~
import java.io.IOException;
import java.net.Socket;
public class ConnectionTest {
private static boolean available(int port) {
System.out.println("--------------Testing port " + port);
Socket s = null;
try {
s = new Socket("localhost", port);
// If the code makes it this far without an exception it means
// something is using the port and has responded.
System.out.println("--------------Port " + port + " is not available");
return false;
} catch (IOException e) {
System.out.println("--------------Port " + port + " is available");
return true;
} finally {
if( s != null){
try {
s.close();
} catch (IOException e) {
throw new RuntimeException("You should handle this error." , e);
}
}
}
}
public static void main(String[] args) {
System.out.println (available (1234)); // check if someone is on the port
}
}
还
private void closeLink() {
try{
out.println ("bye"); //tell server client is disconnecting
sock.close ();
}
catch (Exception e){
System.out.println (e);
}
System.exit(0);
}
于 2013-08-17T15:44:48.620 回答