public class ServerDemo { private OutputStream os; private InputStream is; private DataInputStream dis; // 建立连接 public void setupServer(int port) { try { ServerSocket ss = new ServerSocket(port); System.out.println("开始服务"); while (true) { Socket sc = ss.accept(); System.out.println("已连接 " + sc.getRemoteSocketAddress()); // 等待从客户端传过来的消息 // 调用处理连接来处理连接 communicationProcess(sc); } } catch (Exception e) { e.printStackTrace(); } }改为支持异地登陆
时间: 2024-03-31 20:35:53 浏览: 52
TCPServer.zip_TCP/IP协议栈_Java_
要支持异地登录,可以考虑在建立连接时记录客户端的IP地址和端口号,每次通信时验证客户端的IP地址和端口号是否与之前记录的一致。如果不一致,就说明客户端处于异地登录状态,可以选择断开连接或者进行其他处理。
修改代码如下:
public class ServerDemo {
private Map<String, Socket> clientMap; // 记录客户端的IP地址和Socket连接
private int port;
public ServerDemo(int port) {
this.port = port;
clientMap = new HashMap<>();
}
// 建立连接
public void setupServer() {
try {
ServerSocket ss = new ServerSocket(port);
System.out.println("开始服务");
while (true) {
Socket sc = ss.accept();
System.out.println("已连接 " + sc.getRemoteSocketAddress());
// 验证客户端是否处于异地登录状态
if (checkRemoteAddress(sc)) {
// 记录客户端的IP地址和Socket连接
String remoteAddress = sc.getInetAddress().getHostAddress();
clientMap.put(remoteAddress, sc);
// 调用处理连接来处理连接
communicationProcess(sc);
} else {
// 异地登录,断开连接
System.err.println("异地登录,断开连接 " + sc.getRemoteSocketAddress());
sc.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 验证客户端是否处于异地登录状态
private boolean checkRemoteAddress(Socket sc) {
String remoteAddress = sc.getInetAddress().getHostAddress();
if (clientMap.containsKey(remoteAddress)) {
Socket socket = clientMap.get(remoteAddress);
if (!socket.getPort().equals(sc.getPort())) {
return false;
}
}
return true;
}
// 处理连接
private void communicationProcess(Socket sc) throws IOException {
// 获取输入输出流
os = sc.getOutputStream();
is = sc.getInputStream();
dis = new DataInputStream(is);
// 处理消息
// ...
}
}
阅读全文