通过 Internet 连接到 ServerSocket 时遇到问题 [英] trouble connecting to ServerSocket over the internet
本文介绍了通过 Internet 连接到 ServerSocket 时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,我已经创建了一个简单的聊天室应用程序,但是我无法连接到服务器来发送和接收数据,这是我的代码的一部分:
hello guys I've created a simple chat room app but I can't connect to server to send and receive data, here is part of my code:
服务器端:
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 连接上工作.
It does work on a LAN connection.
请帮帮我...
推荐答案
错误是出现在客户端还是服务器应用中?
Does the error appear in client or server application?
也许这可以帮助您:
- 禁用防火墙
- 检查是否有任何其他应用程序使用该端口(可能更改端口)
- 只是一个想法:在没有 lambda 的情况下尝试一下,它刚刚发布,有时会发生错误(例如在持久性中)
最好的问候
这篇关于通过 Internet 连接到 ServerSocket 时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文