gpt4 book ai didi

java - ServerSocket循环中没有接收到数据

转载 作者:行者123 更新时间:2023-12-02 03:40:03 26 4
gpt4 key购买 nike

我使用 ServerSocket 在 while 循环中从客户端获取数据,它在第一次运行时有效,但在第二轮后失败。

我做了一些搜索,但仍然无法弄清楚发生了什么。

服务器端代码

package com.gorilla.main;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server2 {

public static void main(String[] args) throws Exception {

ServerSocket serverSocket = new ServerSocket(44444);

while(true){

System.out.println("another round");

Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();

System.out.println("available: "+ inputStream.available());

byte[] b = new byte[inputStream.available()];

inputStream.read(b);

System.out.println(new String(b));
System.out.println("=======================");

socket.close();
}
}
}

客户端代码

package com.gorilla.main;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client2 {

public static void main(String [] args) throws Exception{

Socket socket = new Socket("127.0.0.1", 44444);
String s = "Hello World";
byte [] b = s.getBytes();
socket.getOutputStream().write(b);;
socket.close();

}
}

以及我运行客户端 3 次后服务器端控制台的输出。

another round
available: 11
Hello World
=======================
another round
available: 0

=======================
another round
available: 0

=======================
another round

如有任何建议,我们将不胜感激。谢谢。

最佳答案

您使用 InputStream.available()调整缓冲区的大小,这不是从套接字读取数据的方式。您应该分配一个缓冲区(通常静态调整大小,或者可以配置)并循环读取

// server code
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) > -1) {
// do something
}

InputStream.available() 的 Javadoc:

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

如果您的协议(protocol)是基于文本的,您可以将套接字的输入流包装在 Scanner 中。因此循环就变成了

while (scanner.hasNextLine()) {
String line = scanner.next();
}

关于java - ServerSocket循环中没有接收到数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36932693/

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