gpt4 book ai didi

java - 无法通过互联网连接到 ServerSocket

转载 作者:行者123 更新时间:2023-11-30 03:57:28 25 4
gpt4 key购买 nike

大家好,我创建了一个简单的聊天室应用程序,但无法连接到服务器来发送和接收数据,这是我的代码的一部分:

服务器端:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.regex.Pattern;

public class Listener {

public static void start() {
try {
final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(true);
serverSocketChannel.socket().bind(new InetSocketAddress(GetConfigs.getServerListenerPort()));
final List<Operator> operators = new ArrayList<>();
final int nOperators = 64;
for (int i = 0; i < nOperators; i++) {
operators.add(i, new Operator());
}
final int parallelism = Runtime.getRuntime().availableProcessors();
ForkJoinPool pool = new ForkJoinPool(parallelism);
pool.submit(() -> new Thread(() -> {
int i = 0;
while (true) {
try {
operators.get(i).newOperation(serverSocketChannel.accept());
i++;
if (i == nOperators) {
i = 0;
}
} catch (IOException ignored) {
}
}
})).fork().invoke().start();
} catch (IOException e) {
Logging.log.error(e);
}
}

客户端:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.regex.Pattern;

public class ConnectServer {

private static final String SERVER_ADDRESS = GetConfigs.getServerIPAddress();
private static final int SERVER_LISTENER_PORT = GetConfigs.getServerListenerPort();

private StringBuilder result = new StringBuilder();

private void connect() {
result.delete(0, result.length());
try {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(true);
if (socketChannel.connect(new InetSocketAddress(InetAddress.getByName(SERVER_ADDRESS), SERVER_LISTENER_PORT))) {
DataOutputStream dos = new DataOutputStream(socketChannel.socket().getOutputStream());
DataInputStream dis = new DataInputStream(socketChannel.socket().getInputStream());
dos.writeUTF("...");
result.append(String.valueOf(dis.readUTF()));
dos.close();
dis.close();
socketChannel.close();
}
} catch (IOException ex) {
//...
}
}

}

它确实可以在 LAN 连接上工作。

请帮助我...

最佳答案

这是一个简单的测试。通过 SSH 连接到 LAN 之外的计算机,即您无法连接的计算机。尝试两件事:

ping <ip address you connect to>

telnet <ip address you connect to> <port you connect to>

如果 ping 失败,则您可能正在使用“内部”IP 地址,例如 192.168.x.y(或其他类似地址)。尝试使用http://www.whatismyip.com/从您的服务器计算机。

如果 ping 成功而 telnet 失败,则可能存在防火墙问题:请在路由器上设置端口转发,在防火墙上戳一个洞,然后执行其他需要的操作。到底需要什么取决于您的具体设置。

关于java - 无法通过互联网连接到 ServerSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22821056/

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