0
server.js
var net = require('net');
var client = net.connect(5151, 'localhost', function() {
  console.log("Hello from NodeJs");
});
client.on('error', function(ex) {
  console.log("handled error");
  console.log(ex);
});

test.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class nodeListeners {

    public static void main(String[] args) {
        ServerSocket server;
        Socket client;
        InputStream input;

        try {
            server = new ServerSocket(5151);
            client = server.accept();

            input = client.getInputStream();
            String inputString = nodeListeners.inputStreamAsString(input);

            System.out.println(inputString);

            client.close();
            server.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String inputStreamAsString(InputStream stream) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }

        br.close();
        return sb.toString();
    }

}

I am working on this similar application Node->Java Sending data from node.js to Java using sockets from the error I see my connection is refused since the port on Java side is not open. How can I open the port 5151 on java side?

Community
  • 1
  • 1
LisaA
  • 31
  • 2
  • 7

1 Answers1

0

Please, try to use some other port, like 1010. It worked for me on 5151. Try to put a breakpoints and debug your java server side. Also accept on the server side ideally should be happening in the while loop, because in current implementation you will be able to answer only one connection.

You can do

netstat -abno

To check if the port is beeing listened to

Dennis R
  • 1,769
  • 12
  • 13