【发布时间】:2017-08-26 06:17:04
【问题描述】:
我是 JAVA 中的套接字新手。最近,我正在尝试构建一个服务器-客户端程序,客户端可以从服务器端的字典中搜索一个单词,服务器会将单词的定义返回给客户端。服务端代码如下:
public class DictionaryServer {
private static int port;
private static String dicFile;
static Map<String, String> dictionary = new HashMap<String, String>();
int userCounter = 0;
public static void main(String[] args) {
//check if starting the server in valid format
if (args.length != 2) {
System.err.println("Invalid format to start DictionaryServer");
System.err.println("Usage: java DictionaryServer <port number> <the name of dictionary>");
System.exit(1);
}
port = Integer.parseInt(args[0]);
dicFile = args[1];
try{
System.out.println("IP: " + InetAddress.getLocalHost());
System.out.println("port: " + port);
}
catch(UnknownHostException e){
e.printStackTrace();
}
DictionaryServer s = new DictionaryServer();
s.server(port, dicFile);
}
public void server(int port, String dicFile) {
ServerSocketFactory serverSocket = ServerSocketFactory.getDefault();
try(ServerSocket server = serverSocket.createServerSocket(port)){
System.out.println("Server IP: " + server.getInetAddress());
System.out.println("Listening for client connections...");
while(true){
Socket client = server.accept();
System.out.println("Client \"" + client.getRemoteSocketAddress().toString()
+ "\""+ " is connecting.");
Thread t = new Thread(() -> service(client, dicFile));
t.start();
}
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
public void service(Socket client, String dicFile){
try(Socket clientSocket = client){
// Input and Output stream of the client
DataInputStream input = new DataInputStream(
clientSocket.getInputStream());
DataOutputStream output = new DataOutputStream(
clientSocket.getOutputStream());
//check request
int action = input.readInt(); //1:add, 2:remove, 3:query
String word = input.readUTF();
//choose action
Dic d = new Dic(dicFile);
switch(action){
case 1: //add
String definition = input.readUTF();
output.writeUTF(d.add(word, definition, dicFile));
break;
case 2: //remove
output.writeUTF(d.remove(word, dicFile));
break;
case 3: //query
output.writeUTF(d.query(word, dicFile));
break;
}
}
catch(IOException e){
String message=e.getMessage();
System.out.println(message);
System.out.println();
}
}
当我尝试重新启动服务器程序时遇到错误:java.net.BindException: Address already in use (Bind failed)
例如,上次我使用端口 4000 执行服务器程序并且它可以工作,但是如果我想再次使用相同的端口执行服务器程序,就会出现异常。我通过终端中的“lsof -i:4000”检查了端口 4000 在做什么,它告诉我:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 19683 Andy 7u IPv6 0x43e8f876eb74b731 0t0 TCP *:terabase (LISTEN)
有谁知道我该如何解决这个问题?谢谢!
【问题讨论】:
-
一旦应用程序终止,端口最终被操作系统释放。只是需要一些时间。
-
你必须杀死之前运行的服务器或者让你的端口在运行时可以配置为不同
-
感谢您的回复。但我已经等了很长时间,但他们还在听。当我通过添加一些代码退出服务器程序时,是否可以终止它们?因为没有唯一可行的方法是关闭我的 Eclipse。
-
在其他非守护线程仍在运行时,杀死主线程并不会杀死整个 JVM。试试
Thread.setDaemon(true)。欲了解更多信息,请参阅stackoverflow.com/a/2213348/2920861
标签: java sockets exception server serversocket