我正在尝试编写一个基本的服务器 - 客户端Java应用程序。但是,我总是得到一条消息“无论我使用什么端口,”端口13244上的套接字绑定失败:地址已经在使用(错误= 98)“错误。
我附上了我的应用程序的源代码,只是想知道我正在犯的是非常愚蠢的错误。
非常感谢!
干杯, Ĵ
/**
* 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.");
}
}
答案 0 :(得分:13)
你做start()
两次。您无法启动在同一端口上侦听的两台服务器。
答案 1 :(得分:9)
你两次调用test.start(),第二次失败,因为第一次抓住套接字。