gpt4 book ai didi

java - 无法从通过 SocketChannel 接收的消息中提取正确的信息

转载 作者:行者123 更新时间:2023-12-02 07:07:18 24 4
gpt4 key购买 nike

我正在发送一个已使用 DataOutput 流转换为字节的字符串

// creates a client socket which connects to the first successor's server.
Socket clientSocket = new Socket(host, succ1_port);

// send the output_string to the first successor.
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(output_string);

然后通过 SocketChannel 接收它们:

// accept connection
SocketChannel connectionSocket = tcpserver.accept(); // tcpserver is a ServerSocketChannel

ByteBuffer buf = ByteBuffer.allocate(48);

// store and print no. of bytes read
int bytes_read = connectionSocket.read(buf);
System.out.println("bytes read = " +bytes_read);
String from_client_string = new String(buf.array(), Charset.forName("UTF-8"));

收到的消息始终采用“XXXX XXX”格式,其中 X 是 0-9 之间的任意数字。

然后我尝试将这些消息分成两部分:

Pattern p = Pattern.compile("([0-9]{4}) ([0-9]{3})"); 
Matcher m = p.matcher(from_client_string);

if (m.matches()){
int filename = Integer.parseInt(m.group(1));
int hash = Integer.parseInt(m.group(2));
System.out.println("filename = " +filename);
System.out.println("hash = " +hash);
else
System.out.println("no match");

问题是,有时当我打印出从字节缓冲区转换而来的字符串时,它的值会发生变化...通常它是正确的,如“1234 210”,但在其他情况下它可能会剪掉一个数字并显示“1234 21” 。然而,即使它是正确的,我也没有得到匹配?我还发现正在读取的字节数总是在变化......

有人知道这里的问题是什么吗?

感谢您的帮助。

最佳答案

您应该继续循环读取套接字,直到它关闭。如果没有可用字节,则读取将被阻止,因此请确保关闭另一端的连接。

客户端也是如此

// creates a client socket which connects to the first successor's server.
Socket clientSocket = new Socket(host, succ1_port);

// send the output_string to the first successor.
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(output_string);
outToServer.close();
clientSocket.close();

在服务器端:

// accept connection
SocketChannel connectionSocket = tcpserver.accept(); // tcpserver is a ServerSocketChannel

ByteBuffer buf = ByteBuffer.allocate(48);

// store and print no. of bytes read
String result="";
while(connectionSocket.isOpen()){
int bytes_read = connectionSocket.read(buf);
System.out.println("bytes read = " +bytes_read);
String from_client_string = new String(buf.array(),0,bytes_read Charset.forName("UTF-8"));
reulst+= from_client_string;

}}

关于java - 无法从通过 SocketChannel 接收的消息中提取正确的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15939774/

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