大家好我已经创建了一个简单的聊天室应用程序,但我无法连接到服务器来发送和接收数据,这是我的代码的一部分:
服务器端:
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连接。
请帮帮我......
答案 0 :(得分:0)
错误是否出现在客户端或服务器应用程序中?
也许这可以帮到你:
祝你好运