Communicate JS Node with java via socket

Asked

Viewed 416 times

1

I would like to ask a question on how to communicate 2 servers, one being nodejs and the other being java.

I would like to move information json between the 2 using socket support.

I was able to send a java information to the Node and receive it decoding the Base64, but to send another nodejs message to the java receiving I’m not getting.. Can anyone help?

Code:

  var net = require('net');

  var HOST = '127.0.0.1';
  var PORT = 6969;

   global.Buffer = global.Buffer || require('buffer').Buffer;

function Utf8ArrayToStr(array) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = array.length;
    i = 0;
    while(i < len) {
    c = array[i++];
    switch(c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                       ((char2 & 0x3F) << 6) |
                       ((char3 & 0x3F) << 0));
        break;
    }
    }

    return out;
}

  net.createServer(function(sock) {
      console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

      sock.on('data', function(data) {

          console.log(new Buffer(data, 'base64').toString());
          console.log(new Buffer('Mensagem recebida com sucesso').toString('base64'));
          sock.emit('teste');
      });

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

  }).listen(PORT, HOST);

  console.log('Server listening on ' + HOST +':'+ PORT);

Java code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Classe Java (client) para Comunicação com servidor NodeJS Escreve e recebe um
 * simples "echo" -> "mensagem123" by Douglas.Pasqua http://douglaspasqua.com
 */
public class NodeJsEcho {
    // objeto socket
    private Socket socket = null;
    private static boolean close = false;

    public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
        // instancia classe
        NodeJsEcho client = new NodeJsEcho();

        // conexão socket tcp
        String ip = "127.0.0.1";
        int port = 6969;
        client.socketConnect(ip, port);

        // escreve e recebe mensagem
        String message = "mensagem123";

        while(!close){
            System.out.println("Enviando: " + message);
            String retorno = client.echo(message);
            System.out.println("Recebendo: " + retorno);
            close = true;
        }
    }

    // realiza a conexão com o socket
    private void socketConnect(String ip, int port) throws UnknownHostException, IOException {
        System.out.println("[Conectando socket...]");
        this.socket = new Socket(ip, port);
    }

    // escreve e recebe mensagem full no socket (String)
    public String echo(String message) {
        try {
            // out & in
            PrintWriter out = new PrintWriter(getSocket().getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(getSocket().getInputStream()));

            // escreve str no socket e lêr
            out.println(message);
            String retorno = in.readLine();
            return retorno;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    // obtem instância do socket
    private Socket getSocket() {
        return socket;
    }
}

I was able to send a message from java to Node and use a Coder on the other side, but when trying to send one from Node js to java, the message does not reach it, only if I stop the Node server and cut the connection... I believe it is in in.readline();

Can someone help me?

  • How’s your java socket server code?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.