Ad

Can't Send Data From Java Socket Server To NodeJS Client

- 1 answer

I'm making a live connection between a Socket Server (Java) and a Socket Client (NodeJS). This is for a webinterface.

I can send data from NodeJS to Java, but not the other way around. I commented in the code, which positions I mean. I tried it already like you see with out.write("Hello World\n"); (with flush, of course). I tried also with out.println("Hello World"); (with flush, of course).

public class WebHandler {

    private ServerSocket server;
    private static Socket sock;

    public void listen(int port) {
        try {
            server = new ServerSocket(port);
        } catch (IOException e) {
            System.out.println("Could not listen on port " + port);
            System.exit(-1);
        }

        Bukkit.getScheduler().scheduleSyncRepeatingTask(Main.getPlugin(), new BukkitRunnable() {
            @Override
            public void run() {
                try {
                    System.out.println("Waiting for connection");
                    final Socket socket = server.accept();
                    sock = socket;
                    final InputStream inputStream = socket.getInputStream();
                    final InputStreamReader streamReader = new InputStreamReader(inputStream);
                    BufferedReader br = new BufferedReader(streamReader);

                    // readLine blocks until line arrives or socket closes, upon which it returns null
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }

                    WebHandler.sendMessage();

                } catch (IOException e) {
                    System.out.println("Accept failed: " + port);
                    System.exit(-1);
                }
            }
        }, 0, 100);

    }

    // CRITICAL

    public static void sendMessage() {
        try {
            PrintWriter out = new PrintWriter(sock.getOutputStream());
            out.write("Hello World from Java!" + "\n");
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

var net = require('net');

var client = net.connect(9090, 'localhost');
client.setEncoding('utf8');
setInterval(function() {
  console.log("Writing....")
  var ret = client.write('Hello from node.js\n');
  console.log("Wrote", ret)
}, 5000);

// CRITICAL

client.on('data', function(data) {
  console.log('Received: ' + data);
});

Please don't let you distract because of the Bukkit.getScheduler()... It's only a Task Manager. Thanks in advance :D

Ad

Answer

You don't receive a message from java because you have set an interval which will always send messages to the server and the server will be stuck in the while loop.

I would suggest to stop the interval at some point so that sendMessage() will be called.

Ad
source: stackoverflow.com
Ad