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

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()

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

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);
}
}

Related

Socket messaging between Java Client and Python Server

I try to create a Socket messager between a Java Client and Python Server. It works to send a message ("Testdata") from client to server and print it out. But after input and send a message from server to client, I get no output from client. The client 'freezes' and must be terminated.
What is the problem with my client input?
Terminal Server:
py socketServer.py
Connection from: ('127.0.0.1', 57069)
from connected user: Testdata
> Test
send data..
Terminal Client:
java socketClient
Testdata
Python-Server:
import socket
def socket_server():
host = "127.0.0.1"
port = 35100
server_socket = socket.socket()
server_socket.bind((host, port))
server_socket.listen(2)
conn, address = server_socket.accept()
print("Connection from: " + str(address))
while True:
data = conn.recv(1024).decode()
if not data:
break
print("from connected user: " + str(data))
data = input('> ')
conn.send(data.encode())
print("send data...")
conn.close()
if __name__ == '__main__':
socket_server()
Java-Client:
private static void socketTest(){
String hostname = "127.0.0.1";
int port = 35100;
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, false);
BufferedReader input =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
Scanner in = new Scanner(System.in);
String text;
do {
text = in.nextLine();
writer.print(text);
writer.flush();
System.out.println("from server: " + input.readLine());
} while (!text.equals("exit"));
writer.close();
input.close();
socket.close();
}
}
This is because python messages are not explicitly finished with \r\n like #carlos palmas says in this answer.

Java Socket Server hangs while reading data

I have a PHP file talking to a Java socket server, and when I send data over, my java server gets stuck (hung, frozen) on inputLine = in.readLine(). I've debugged and found that it's only when I read data, this happens.
Here's my java method for the server:
public void start_echo_server(int port){
main.getProxy().getConsole().sendMessage(new TextComponent(ChatColor.GOLD + "STARTING SOCKET LISTENER (echo)"));
int portNumber = port;
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
// accepted the connection
main.getProxy().getConsole().sendMessage(new TextComponent(ChatColor.GOLD + "ACCEPTED"));
// in stream
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// outstream
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
String final_line = sb.toString();
main.getProxy().getConsole().sendMessage(new TextComponent(ChatColor.GOLD + "IN: " + final_line));
//String final_ret = parser.parse_message(final_line);
//main.getProxy().getConsole().sendMessage(new TextComponent(ChatColor.GOLD + "FINAL: " + final_ret));
out.println(final_line);
in.close();
out.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And here's my PHP file:
<?php
if( isset($_POST['username']) )
{
$username = $_POST['username'];
parse($username);
}else{
echo "Missing parameters!";
exit();
}
function parse($username){
//Must be same with server
$host = "127.0.0.1";
$port = 59090;
// No Timeout
//Create Socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
//Connect to the server
$result = socket_connect($sock, $host, $port) or die("Could not connect toserver\n");
$message = "player_online ". $username;
//Write to server socket
$len = strlen($message);
socket_write($sock, $message, $len) or die("SENDING ERROR ". $message ." \n");
//Read server respond message
$result = socket_read($sock, 1024) or die("RESPONSE ERROR ". $message ." \n");
echo "Reply From Server :".$result;
//Close the socket
socket_close($sock);
}
?>
The problem is when I do socket_write (writing the data) on the PHP side, but the issue is at the java line while ((inputLine = in.readLine()) != null) {.
Thanks so much!
Solved!
I was reading multiple lines with only one line coming in, while I didn't include a newline (\n) after the message (which signifies that the previous message was a line that is finished).
Replace PHP $message = "player_online ". $username; with $message = "player_online ". $username ."\n";
Also had to replace Java
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
String final_line = sb.toString();
with
String inputLine = in.readLine();
String final_line = inputLine;
Try changing the while condition to something you control as a proof of concept i.e read during 1 minute or so, if that unstucks ypu then do nor read while in.readline but fimd something else, it happened to me on some ssh connection, we then set the while condition to read while channel is open...will try to find that code and add it here if you dont get to somerhing based on the above proof of concept

Java socket - the server response is always null

I have to connect with a server (I donĀ“t have access to the server code) but the transmission protocol (Socket) is:
(client) --> data
ack <-- (server)
data response <-- (server)
(client) --> ack
It's assumed that the server should always respond quickly. I connect to the server, I send the data but the response is NULL and if I debug my code, an exception occurs when I catch the response:
"java.net.SocketException: Software caused connection abort: recv failed"
My code:
public static void main(String[] args){
try{
String order = "datahere";
String responseServer;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket();
InetSocketAddress sa = new InetSocketAddress("XXX.XX.XX.XX", 9300);
clientSocket.connect(sa,500);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(order);
responseServer = inFromServer.readLine();//exception if I try to debug my code
System.out.println("From server: " + responseServer); //responseServer is NULL
clientSocket.close();
} catch (IOException ex) {
System.out.println("Error: "+ex);
}
}
That's wrong? Any idea?
I tried to disable the firewall and also add a rule for the port 9300 but the result is the same.
The client gave me an example code in Vb.Net that it's supposed to work and I try to replicate it in Java.
Code in Vb.Net:
Dim message As String = "datahere";
Try
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
Dim client As New TcpClient(ip, port)
Dim stream As NetworkStream = client.GetStream()
stream.Write(data, 0, data.Length)
data = New [Byte](2048) {}
Dim responseData As [String] = [String].Empty
Dim bytes As Integer = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
stream.Close()
client.Close()
Catch ex As Exception
End Try
SOLUTION:
Socket clientSocket = new Socket();
InetSocketAddress sa = new InetSocketAddress("XXX.XX.XX.XX", 9300);
clientSocket.connect(sa,500);
clientSocket.getOutputStream().write(order.getBytes("ASCII"));
byte[] data = new byte[2048];
int bytes = clientSocket.getInputStream().read(data, 0, data.length);
String responseData = new String(data, 0, bytes, "ASCII");
System.out.println("From server: " + responseData);
//Another way to catch the response:
//InputStreamReader in = new InputStreamReader(clientSocket.getInputStream());
//int data1 = in.read();
//while(data1 != -1) {
// System.out.print((char) data1);
// data1 = in.read();
//}
clientSocket.close();
Here is a translation of your VB code in java
public static void main(String[] args) throws IOException {
String order = "datahere";
// Try-with-resource statement will close your socket automatically
try (Socket clientSocket = new Socket("XXX.XX.XX.XX", 9300)) {
// Send to the sever the order encoded in ASCII
clientSocket.getOutputStream().write(order.getBytes("ASCII"));
// Sleep until we have bytes to read available
while (clientSocket.getInputStream().available() == 0) {
Thread.sleep(100L);
}
// Create the buffer of exactly the amount of bytes available without blocking
byte[] data = new byte[clientSocket.getInputStream().available()];
// Read the bytes from the server and put it into the buffer
int bytes = clientSocket.getInputStream().read(data, 0, data.length);
// Decode what has been read from the server that was encoded in ASCII
String responseData = new String(data, 0, bytes, "ASCII");
System.out.println("From server: " + responseData);
}
}
DataInputStream dis = new DataInputStream( new InputStreamReader(clientSocket.getInputStream()));
while(dis.available()>0){
//reads characters encoded with modified UTF-8
String temp = dis.readUTF();
System.out.print(temp+" ");
}
try to use a dataInputStream instead of bufferedReader and use readUTF() method in dataInputStream to read UTF characters.

Java / JSP Send TCP packet and wait for response

I'm trying to send a TCP packet. It sends correctly to the server but sender is not getting response (server is sending response back correctly). Client doesn't even process code afeter sending the packet...
Socket socket = new Socket (ip, port);
PrintWriter mOut = new PrintWriter(socket.getOutputStream(), true);
mOut.print("DSPSYSSTS");
//Everything works fine until here
BufferedReader mIn = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
String fromClient = mIn.readLine();
out.println ("Client Message: " + fromClient);
mOut.close();
mIn.close ();
socket.close ();
The JSP doesn't print the input and it remains loading forever. What's wrong?
Returning String of systemRequest.request in below code
ReadSpoolFile readSplf = new ReadSpoolFile(splfArray.get(0));
String splfContent = readSplf.read();
GetSystemStatus getSysSts = new GetSystemStatus();
String systemStatus = getSysSts.get(splfContent);
return systemStatus + "\r\n";
Server side Response:
String response = systemRequests.request(message, SystemRequests.SILENT_OFF);
ChannelBuffer mCbResponse;
if(response != null){
mCbResponse = ChannelBuffers.copiedBuffer(response.getBytes());
mChannel.write(mCbResponse); //<------Write response
Try this:
mOut.print("DSPSYSSTS");
mOut.flush();
...

socket server not sending data to php client

I am trying to create a communication between a socket server in java and a php client however apparently no data is sent from server to client. I have tried plenty of methods for writing data to socket but none of those did work although i am able to send data from client to server.
Server side code
int port = 5566, maxConnections = 0;
int nrCon=0;
ServerSocket listener = new ServerSocket(port);
Socket server;
while((nrCon++<maxConnections)|| (maxConnections ==0)){
server = listener.accept();
BufferedReader in = new BufferedReader (new InputStreamReader(server.getInputStream()));
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( server.getOutputStream() ) );
//PrintWriter out = new PrintWriter(server.getOutputStream(), true);
//ObjectOutputStream oos = new ObjectOutputStream(server.getOutputStream());
//DataOutputStream os = new DataOutputStream(server.getOutputStream());
String line, data="";
while((line = in.readLine())!= null ){
System.out.println("wowowoowow");
data = data + line;
String[] coords = data.split(" ");
}
out.print("ROUTE DIJKSTRA: \n");
//out.flush();
//os.writeUTF("testetstets");
client side code
$PORT = 5566;
$HOST = "localhost";
$sock = socket_create(AF_INET, SOCK_STREAM, 0)
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT)
or die("error: could not connect to host\n");
socket_set_nonblock($sock);
if ( $_POST['v_lat']=="undefined" && $_POST['v_lng']=="undefined" ){
$text = "$sLng $sLat $dLng $dLat";
}else{
$vLat = $_POST['v_lat'];
$vLng = $_POST['v_lng'];
$text = "$sLng $sLat $vLng $vLat $dLng $dLat";
}
$sent = socket_write($sock, $text, strlen($text)+1);
$sock_err = socket_last_error($sock);
if ($sent === false) {
echo "could not send data to server\n";
break;
}else {
echo "sent ".$sent." bytes\n";
}
echo "sock error send: ".$sock_err." \n";
$result = socket_read ($sock, 2048);
$sock_err = socket_last_error($sock);
echo "sock err: ".$sock_err." \n";
echo "Reply From Server :".$result;
What i do get from sock_err call is the error code 10035 which is apparently for server not sending the data no matter how many socket writing data methods i tried.
I ran out of ideas.

Categories

Resources