gpt4 book ai didi

java - 接收来自客户端的消息

转载 作者:行者123 更新时间:2023-12-01 08:56:50 24 4
gpt4 key购买 nike

我编写了以下连接到客户端的服务器:

ServerSocket server = null;

try
{
server = new ServerSocket(4040);

while (isServerListening)
{
Socket clientSocket = server.accept();

// Send bytes to the Client
ServerOutputStream = clientSocket.getOutputStream();

byte[] bytes = "I am a Server".getBytes();
ServerOutputStream.write(bytes);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
// close socket here
}

该服务器在 server.accept() 行停止并等待下一个客户端连接。同时我想阅读从客户端收到的消息。

几年前,我通过事件处理程序用不同的语言进行了套接字编程,但在这里我似乎需要一种不同的方法。

我的问题是:我需要另一个线程来完成此任务吗?有没有替代方案,例如非阻塞模式?

最佳答案

My question is: Would I need another thread for this task?

一种方法是为每个客户端连接使用一个线程。应用程序方法以无限循环运行服务器,监听端口。当请求连接时,它会生成一个新线程来执行服务并立即返回监听状态。

ServerSocket listener = new ServerSocket(9898);
try {
while (true) {
new Handler(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}

处理特定套接字上的请求的线程。

private static class Handler extends Thread {
private Socket socket;
private int clientNumber;

public Handler(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
}

public void run() {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

while (true) {
String input = in.readLine();
...
}
} catch (IOException e) {
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what's going on?");
}
}
}
}

Is there an alternative e.g. non-blocking mode?

对于非阻塞套接字 channel ,服务器套接字必须向选择器注册才能执行某些操作。默认情况下,服务器套接字 channel 是阻塞 channel 。要使其成为非阻塞 channel ,请设置以下内容。

channel.configureBlocking(false);

非阻塞服务器程序看起来像......

InetAddress hostIPAddress = InetAddress.getByName("localhost");
int port = 19000;
Selector selector = Selector.open();
ServerSocketChannel channel = ServerSocketChannel.open();
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(hostIPAddress, port));
channel.register(selector, SelectionKey.OP_ACCEPT);

while (true) {
Set keys = selector.selectedKeys();
...
}

非阻塞客户端程序看起来像......

InetAddress serverIPAddress = InetAddress.getByName("localhost");
InetSocketAddress serverAddress = new InetSocketAddress(
serverIPAddress, 19000);
Selector selector = Selector.open();
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(serverAddress);
int operations = SelectionKey.OP_CONNECT | SelectionKey.OP_READ
| SelectionKey.OP_WRITE;
channel.register(selector, operations);

while (true) {
if (selector.select() > 0) {
Set keys = selector.selectedKeys();
...
}
}
channel.close();

关于java - 接收来自客户端的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41991208/

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