Java客户端套接字连接不起作用

时间:2017-08-16 06:50:11

标签: java node.js sockets

所以我尝试使用本指南创建一个可以连接到node.js服务器的java客户端 - > http://mrbool.com/communicating-node-js-and-java-via-sockets/33819。我遵循了所有步骤,但是当我运行代码时,线程会阻塞。我在nodejs服务器上有适当的事件,但是它没有从我的java客户端接收消息。有谁知道为什么会发生这种情况并修复它?

Node.js代码:

var net = require('net');
var host = '127.0.0.1';
var port = 3000;
var server = net.createServer((sock) => {
    console.log("Connected " + sock.remoteAddress + ":" + sock.remotePort);
    sock.on('data', (data) => {
        console.log("Received Data")
        sock.write(data);
    })

    sock.on('close', (data) => {
        console.log('CLOSED ' + sock.remoteAddress + ":" + sock.remotePort);
    });
});

server.listen(port, host);
console.log("listening on " + host + ":" + port);

Java客户端:

import java.io.*;
import java.net.*;
public class Main {
    private Socket clientSocket;
    private BufferedReader input;
    private PrintWriter output;
    String hostName = "127.0.0.1";
    int port = 3000;
    public Main() {
    }

    public static void main(String[] args) {
    Main main = new Main();
    try {
        main.connect();
        String message = "test123";

        System.out.println("Sending " + message);
        String returnStr = main.echo(message);
        System.out.println(returnStr);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
        main.getSocket().close();
        } catch (IOException e) {
        e.printStackTrace();
        }
    }
    }

    public void connect() throws UnknownHostException, IOException {
    clientSocket = new Socket(hostName, port);
    }


    public String echo(String message) throws IOException {
    try(PrintWriter out = new PrintWriter(clientSocket.getOutputStream()); 
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));){
        String returnStr = null;
        System.out.println("Attempting to send");
        out.print(message);
        returnStr = in.readLine();
        return returnStr;
    }
    }

    public Socket getSocket() {
    return clientSocket;
    }
}

命令提示符输出:

listening on 127.0.0.1:3000
Connected 127.0.0.1:52572

1 个答案:

答案 0 :(得分:0)

'connect'工作正常。问题出在其他地方。

  1. 您正在阅读一行,readLine()
  2. 您没有发送一行:您正在使用print()
  3. Javascript服务器将回显您发送的任何内容,但在客户端执行之前不会关闭套接字。
  4. 客户端没有关闭套接字,因为它在readLine()中被阻塞,等待从不发送的行终止符。
  5. 使用println()代替print()