Java / JSP Send TCP packet and wait for response - java

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

Related

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

Java: client-server socket programming - server returns, but not receiving at client

I've a client-server connection. The client sends out request to server in a predefined format to initiate some processing at server. Server does this processing and then returns the result in predefined format to client.
Processing at server may take upto 15 mins.
I'm using reqObject.toString() to convert the request/response to string and then send through network using readUTF and writeUTF (reading the whole buffer).
Now the issue:
Data send by client is received properly and the processing happens. Once that is done, if the processing takes LESSTHAN 5 mins, once server sends the data, client receives it normally.
But if processing takes MORETHAN 5-6 mins, server sends back data, but client doesnt receive it (times out after given timeout period).
Code snippet:
Client:
Socket server = null;
OutputStream outToServer = null;
DataOutputStream out = null;
InputStream inFromServer = null;
DataInputStream in = null;
if(msg != null){
try
{
server = new Socket(serverIp, serverPort);
server.setSoTimeout(1000 * 60 * timeoutInMins); //set to 30 mins
outToServer = server.getOutputStream();
out = new DataOutputStream(outToServer);
out.writeUTF(msg);
out.flush();
// now wait for Server reply
inFromServer = server.getInputStream();
in = new DataInputStream(inFromServer);
responseString = in.readUTF();
// do something with response
}
Server:
ServerSocket serverSocket = null;
Socket client = null;
try{
serverSocket = new ServerSocket(port);
} catch (Exception e) {//log this}
try
{
while(true)
{
client = serverSocket.accept();
if(client.getRemoteSocketAddress() != null){
try{
ReqObject request = getRequest(client);
// do processing. this may take upto 10-15 mins at max
sendBackResponse(client, request);
}
// do remaining
private void sendBackResponse(Socket client, ReqObject result) throws IOException {
DataOutputStream out = null;
try{
out = new DataOutputStream(client.getOutputStream());
String outToClient = result.toString();
out.writeUTF(outToClient);
out.flush();
} finally {
try{out.close();}catch(IOException e){}
}
}
private ReqObject getRequest(Socket client) throws IOException {
DataInputStream in = null;
in = new DataInputStream(client.getInputStream());
String incoming = in.readUTF();
return convertMessageToRequest(incoming);
}
The connection was getting disconnected/blocked by a firewall which was in between, after 5 mins of inactivity.
To overcome this, I started sending heartbeat message (with junk data) every 2 minute. This kept the connection alive till the operation completed.
Note: The keepalive() method provided by java didn't help..

Java socket does not receive data

I have to write server application that request questions from client and receives an answer. This is my client code:
clientSocket = new Socket("localhost", 1234);
System.err.println("Client started");
//get questions
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
Question q = (Question)in.readObject();
//send answer
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
out.print("a1");
out.flush();
and server code:
//sending questions
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
List<Question> quest = Questions.getInstance().getQuestions();
out.writeObject(quest.get(0));
out.flush();
//get answer
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String temp = null;
while ((temp = in.readLine()) == null) {}
String answer = temp;
Questions successfully sent and later received by client, but server never get answer (infinite loop while reading temp variable). What is the problem?
Your calling out.print("a1"); on the client, but reading a line on the server using in.readLine(). Shouldn't you be writing out using println() on the client, else the server never gets to the end of the line? – CodeChimp Nov 21 at 21:07
Thanks for CodeChimp

Java Sockets - Server hangs after client sends its response

Just trying to get a handle on sockets. The server and client are running in two different programs.
They seem to be connecting fine to each other but the client will not properly send its output to the server. The server just hangs. Here's the code:
Server:
private ServerSocket serverSocket;
private Socket client;
public void run() throws Exception {
serverSocket = new ServerSocket(20005);
while(currentState == Game.State.NORMAL) {
client = serverSocket.accept();
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String clientInput = in.readLine();
// Takes the client input string and does some simple game logic that returns a Gson object
Gson serverResponse = processInput(clientInput);
out.write(serverResponse.toString());
out.flush();
}
}
Client:
Socket clientSocket;
void run() throws Exception {
clientSocket = new Socket("192.168.0.24", 20005);
PrintWriter out;
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Print the state of the game - returns false if state is win or lose.
while(printState()) {
out = new PrintWriter(clientSocket.getOutputStream(), true);
// This method just takes some input from the console
String clientInput = getInput();
out.write(clientInput);
out.flush();
String serverResponse = in.readLine();
updateState(serverResponse);
}
}
}
There is some underlying game logic that is happening but it's pretty minor and should be irrelevant. I imagine I am just misunderstanding something fundamental here.
Thanks all.
Make sure you send a newline character to match the in.readLine() statement in the Server.
out.write(clientInput + "\n");
The same applys when sending data from Server->Client.

Client doesn't receive output from server's DataOutputStream

I'm currently attempting to code my first client>server system to transmit packets containing strings back and forth through a network. However I'm having a problem in that the following is happening:
The client sends message to the server, the server receives the message, processes the message, and then supposedly sends a reply to the client, but the client never receives this message and hangs waiting for a response from the server. Here is the code:
SERVER:
public static void handlePackets() throws Exception {
String clientSentence;
String returnToClient;
ServerSocket welcomeSocket = new ServerSocket(1337);
System.out.println("Packet receiver initialized!");
while (run) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received Packet: " + clientSentence);
System.out.println("Compiling return to client.");
returnToClient = "";
if (clientSentence.startsWith("Handshake-")) {
returnToClient = handleHandShake(clientSentence);
}
outToClient.writeBytes(returnToClient);
System.out.println("Sent client response " + returnToClient);
}
welcomeSocket.close();
}
CLIENT:
public static String sendTCP(String host, String content) {
try {
System.out.println("Packet sender sending TCP packet " + content);
String serverResponse;
Socket clientSocket = new Socket(host, 1337);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(content + '\n');
System.out.println("Send data to sever. Awaiting response.");
serverResponse = inFromServer.readLine();
clientSocket.close();
System.out.println("Server response received " + serverResponse + " result was returned to caller.");
return serverResponse;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
The client is calling readLine() but the server isn't writing a line, just bytes, so the client is waiting forever for the line terminator. Append '\n' to the server's reply. Also the server should close the accepted socket once it's finished with it. Do this by closing whatever writer or output stream you have wrapped around it, not by closing the socket itself.
You should use BufferedOutputStream instead of DataOutputStream. It will work for simple data as is but you are liable to charset problems if you don't fix it sooner or later. In general you should always use symmetric input and output streams or readers.
1) You should close or flush outToServer / outToClient
2) When you read with BufferedReader you should write with BufferedWriter, not DataOutputStream

Categories

Resources