NodeJS Socket未关闭连接时无法发送数据问题求助
Spigot Socket服务器与Node.js客户端通信问题解决
问题根源
- Java服务器的
inputStreamAsString方法依赖BufferedReader.readLine(),这个方法必须读取到换行符(\n)或者输入流关闭才会返回结果。 - 当Node.js客户端不调用
client.end()时,仅发送data1但无换行符,服务器的readLine()会持续阻塞等待,因此收不到数据。 - 调用
client.end()时,输入流被关闭,readLine()触发返回,但连接也随之断开,导致每次发送都需重建连接。 - 额外注意:你的客户端代码写的端口是
12343,但Java服务器监听的是12243,端口必须统一才能正常通信。
解决方案
方案1:客户端发送时添加换行符(适配现有服务器逻辑)
修改Node.js客户端代码,在发送的数据末尾追加换行符,让服务器的readLine()能立即读取内容,同时可选择是否保持连接:
var net = require('net'); var client = net.connect(12243, 'localhost'); // 统一端口为服务器监听的12243 client.write('data1\n'); // 添加换行符触发服务器读取 // 若需要保持连接后续发送数据,不要调用client.end() // 示例:1秒后再次发送 // setTimeout(() => { // client.write('data2\n'); // }, 1000); // 若为单次发送后关闭连接,再调用end // client.end();
方案2:修改服务器读取逻辑(支持无换行/长连接)
如果不想依赖换行符,可改写服务器的流读取逻辑,直接读取字节流;若要支持长连接(客户端保持连接多次发送),还需调整连接处理逻辑:
// 修改inputStreamAsString方法,不再依赖readLine() public static String inputStreamAsString(InputStream stream) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[1024]; // 读取流中所有可用数据(长连接下需自定义结束标识) while ((nRead = stream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return new String(buffer.toByteArray(), StandardCharsets.UTF_8); } // 修改handleConnection方法,支持长连接持续监听 private void handleConnection(Socket clientSocket) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String line; // 持续读取直到客户端主动关闭连接 while ((line = br.readLine()) != null) { System.out.println("收到数据:" + line); // 可选:给客户端回复消息 // OutputStream output = clientSocket.getOutputStream(); // output.write("已接收数据\n".getBytes(StandardCharsets.UTF_8)); // output.flush(); } // 客户端关闭连接后再释放资源 br.close(); clientSocket.close(); }
内容的提问来源于stack exchange,提问作者elixs
相关产品推荐
相关产品推荐

