vitorvr
vitorvr

Reputation: 655

Java Socket Receive and Send data (JSON-RPC 2.0)

I need to write a program using Java to connect a socket, send authenticate data and receive the answer. I have a code in Python that works and I'm using this as an example.

I'm able to connect but after send data I didn't receive anything.

Below the java code that I wrote:

String hostname = "remoteHost";
int port = 4200;

Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

JSONObject json = new JSONObject();
JSONObject params = new JSONObject();

params.put("code", "authCode");

json.put("jsonrpc", "2.0");
json.put("method", "authenticate");
json.put("params", params);
json.put("id", "0");

out.write(json.toString());

System.out.println(in.readLine());

Below the example in Python:

import socket, json
from dateutil import parser

host = "app.sensemetrics.com"
port = 4200
apiCode = "YourAPIKey"

# Open a new socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

# Send the authentication request
handshake = json.dumps({
    "jsonrpc": "2.0",
    "method": "authenticate",
    "params": {
        "code" : apiCode
    },
    "id": 0
})
s.send(handshake)

# Parse the response
jsonFrame = decodeOneJsonFrame(s)
response = json.loads(jsonFrame)
print("\r\nHandshake Exchange:\r\n" + "     --> " + handshake + "\r\n" + "     <-- " + jsonFrame)

# Close the socket connection
s.close()

Upvotes: 0

Views: 597

Answers (2)

V&#252;sal
V&#252;sal

Reputation: 2706

Use try-with-resources to automatically close open resources and OutputStream.flush - to flush the data to the stream.

Modify your code as below:

String hostname = "remoteHost";
int port = 4200;

JSONObject json = new JSONObject();
JSONObject params = new JSONObject();
params.put("code", "authCode");
json.put("jsonrpc", "2.0");
json.put("method", "authenticate");
json.put("params", params);
json.put("id", "0");

try (
    Socket socket = new Socket(hostname, port);
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
    out.write(json.toString());
    out.flush();

    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
}

Upvotes: 1

rkosegi
rkosegi

Reputation: 14678

out.write(json.toString());

I think you should also call out.flush().

Don't forget to call flush on other side too, after writing response so you can read it with System.out.println(in.readLine());

See here

Upvotes: 1

Related Questions