gpt4 book ai didi

Java Socket 编程 - 地址已被使用 (errno=98)

转载 作者:行者123 更新时间:2023-12-03 20:22:31 25 4
gpt4 key购买 nike

我正在尝试编写一个基本的服务器-客户端 Java 应用程序。但是,无论我使用哪个端口,我总是收到“10 端口 13244 上的套接字绑定(bind)失败:地址已在使用 (errno=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()。您不能在同一个端口上启动两个服务器。

关于Java Socket 编程 - 地址已被使用 (errno=98),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/852896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com