[英]Java Socket Programming - Address already in use (errno=98)
我正在嘗試編寫一個基本的服務器 - 客戶端Java應用程序。 但是,無論我使用什么端口,我總是得到“端口13244上的套接字綁定失敗:地址已經在使用(錯誤= 98)”錯誤的消息。
我附上了我的應用程序的源代碼,只是想知道我正在犯的是非常愚蠢的錯誤。
非常感謝!
干杯,J
/**
* Command process test.
*/
import java.net.*;
import java.io.*;
public class CommandProcessTest implements Runnable{
private static final int PORT = 13244;
private ServerSocket serverSocket;
public static void main(String[] args) {
CommandProcessTest test = new CommandProcessTest();
System.out.println("starting server.");
test.start();
System.out.println("server start up.");
// try {
// test.wait(100);
// } catch(InterruptedException e) {
// }
// Thread client = new Thread(test);
System.out.println("Server start receiving.");
test.start();
System.out.println("Server exit.");
}
private void start() {
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
}
private void server() {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
CommandProcess cp = new CommandProcess(clientSocket);
int cmd = 10;
String arg = "";
cp.sendCommand(cmd);
arg = "hello";
cp.sendCommand(cmd, arg.split(" "));
arg = "hello world";
cp.sendCommand(cmd, arg.split(" "));
arg = "world hello world";
cp.sendCommand(cmd, arg.split(" "));
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
private void client() {
try {
Socket socket = new Socket("localhost", PORT);
CommandProcess cp = new CommandProcess(socket);
while(true) {
int cmd = cp.getCommand();
String[] args = cp.getArguments();
String s = "Command: " + Integer.toString(cmd);
if(args != null) {
for(int i = 0; i < args.length; i++) {
if(args[i] == null) {
break;
}
s += args[i];
}
}
System.out.println(s);
}
} catch(IOException e) {
System.out.println("Would not connect to local host: 444");
System.exit(-1);
}
}
public void run() {
System.out.println("Starting client");
client();
System.out.println("Client startup.");
}
}
你做兩次start()
。 您無法啟動在同一端口上偵聽的兩台服務器。
你調用test.start()兩次,第二次會失敗,因為第一次抓住套接字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.