JAVAのソケットは初めてです。最近、クライアントがサーバー側の辞書から単語を検索できるサーバークライアントプログラムを構築しようとしています。サーバーはその単語の定義をクライアントに返します。サーバー側のコードは、次のとおりです。サーバ側でLISTEN状態からポートを解放する方法
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();
}
}
私はserverprogramを再起動しようとすると、私はエラーでstucked持っています:java.net.BindException:すでに使用中のアドレス(バインドが失敗した)
例えば、ポート4000でサーバプログラムを最後に実行しても動作しましたが、同じポートでサーバプログラムを再度実行したい場合は、例外が表示されます。私に言ったターミナルに:私は、ポート4000は「4000 lsofを-i」:で何をしているか確認
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 19683 Andy 7u IPv6 0x43e8f876eb74b731 0t0 TCP *:terabase (LISTEN)
は、誰もが、私はこの問題を解決する方法を知っていますか?ありがとうございました!
アプリケーションが終了すると、最終的にOSによってポートが解放されます。それはちょうど時間がかかる。 – DyZ
実行中のサーバを強制終了するか、実行時にポートを別のものにするように設定する必要があります –
返信ありがとうございます。しかし、私は長い間待っていましたが、彼らは依然として黙っています。いくつかのコードを追加してサーバープログラムを終了すると、それらを終了することは可能でしょうか?いいえ、私のEclipseを閉じるしかありません。 –