what I'm trying to do is to send some JSON from an Android phone to a Java server, which works fine. The Android/ client side looks like this:
Socket s = new Socket("192.168.0.36", 12390);
s.setSoTimeout(1500);
JSONObject json = new JSONObject();
json.put("emergency", false);
json.put("imei", imei);
json.put("lat", l.getLatitude());
json.put("lon", l.getLongitude());
json.put("acc", l.getAccuracy());
json.put("time", l.getTime());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
out.write(json.toString());
out.flush();
s.close();
The server side is this:
try {
s = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("Could not listen on port: " + port);
System.exit(-1);
}
Socket c = null;
while (true) {
try {
c = s.accept();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine = null;
String result = "";
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
System.out.println(result);
As I said, all of that works. Now I want to send a message back from the server to the client after it received the message from the client.
I extended the code like this, Android/ client side:
Socket s = new Socket("192.168.0.36", 12390);
s.setSoTimeout(1500);
JSONObject json = new JSONObject();
json.put("emergency", false);
json.put("imei", imei);
json.put("lat", l.getLatitude());
json.put("lon", l.getLongitude());
json.put("acc", l.getAccuracy());
json.put("time", l.getTime());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
out.write(json.toString());
out.flush();
String inputLine = null;
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, in.readLine());
result = result.concat(inputLine);
}
And the server side:
try {
s = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("Could not listen on port: " + port);
System.exit(-1);
}
Socket c = null;
while (true) {
try {
c = s.accept();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine = null;
String result = "";
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
System.out.println(result);
PrintWriter out = new PrintWriter(c.getOutputStream());
out.write("Hello phone");
out.flush();
out.close();
On the client side, nothing ever comes in, it hangs on
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, in.readLine());
result = result.concat(inputLine);
}
until the socket times out (never enters the loop). I thought it might be a timing problem, for example the server sending out its reply too early and therefore the client never receiving anything, but i tried to put the out.write("Hello phone"); pretty much anywhere in the code, always the same result. Can it have to do with the socket being obtained from ServerSocket and not being able to send out data? What am I missing here, this is bugging me all day ...
Edit: After Nikolais answer, I tried this (client):
out.write(json.toString());
out.newLine();
out.write("###");
out.flush();
String inputLine = null;
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("###")) {
break;
}
Log.d(TAG, in.readLine());
result = result.concat(inputLine);
}
s.close();
and server:
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
if (inputLine.contains("###")) {
System.out.println("received ###");
out.println("Hello phone");
out.println("###");
out.flush();
break;
}
}
The idea was to send out the message from the server before the client closes the socket. Still doesnt work ... any hints?
On the server side you never get to sending your "Hello phone". Not until client closes the socket, but at that point it's useless. This is because in.readLine() blocks until either data is available or EOF, i.e. socket closed.
You need a way to get out of the reading loop - invent (or adopt) some application-level protocol that would tell you that a whole message is received. Common options are fixed length messages, length prefix, delimited, etc.
Related
My partner system services socket server. They don't share the client module, only test sample data.
First, I tested using telnet program and it's successful.
this image link is the test using telnet program.
But my Java socket client can't receive message from socket server.
this image link is result of my socket program.
Would you help me?
Thanks.
public static void main(String[] args) {
System.out.println("file.encoding: " + System.getProperty("file.encoding"));
try {
Socket socket;
final String HOST = "xx.xx.xx.xxx"; // partner test server
final int PORT = 8994;
try {
socket = new Socket(HOST, PORT);
} catch (IOException ioe) {
System.out.println(">>>");
System.out.println(ioe.getMessage());
System.out.println(">>>");
throw ioe;
}
System.out.println("sending data:");
OutputStream os = socket.getOutputStream();
byte[] b = "xxxx52017082410332310000000020321 ONL00000 080081COP0045 3xxxxxxxxxxxxxxx/jOsBUe5I11C2mtP0j5tPSww==20170824103323 ".getBytes();
for (int i = 0; i < b.length; i++) {
os.write(b[i]);
}
os.flush();
socket.shutdownOutput();
System.out.println(new String(b) + "[END]");
System.out.println("receiving data");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
socket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
I found the solution.
The sever socket program sent byte data, not string line.
Please find below my source code.
Thanks everyone.
socket = new Socket(ip, port);
System.out.println("SEND DATA[" +msg.length() + "] [" + msg + "]");
oout = new BufferedOutputStream(socket.getOutputStream());
iin = new BufferedInputStream(socket.getInputStream());
oout.write(msg.getBytes());
oout.flush();
byte[] buffer = new byte[1156];
System.out.println("RECV DATA");
iin.read(buffer);
System.out.println("RECV DATA [" + new String(buffer) +"]");
I am trying to make a chat system through terminal. One computer acts as server, the other as client.
Here is my code for Client side :
try
(
Socket s = new Socket(hostname,port);
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
) {
String input;
while ((input = stdIn.readLine()) != null)
{
out.println(input);
}
String inputline;
while ((inputline = in.readLine()) != null)
{
System.out.println("Them: " + inputline);
}
// out.close();
// stdIn.close();
// s.close();
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host: " + hostname);
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O");
System.exit(1);
}
Here is my code for Server side:
System.out.println ("New communication thread started.");
try
{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String input;
String inputline;
while ((inputline = in.readLine()) != null)
{
System.out.println("Them: " + inputline);
}
while ((input = stdIn.readLine()) != null)
{
out.println(input);
}
}
catch (IOException exx)
{
System.err.println("Some problem");
System.exit(1);
}
You are using stdIn.readLine() on System.in but that stream can never terminates (of course).
So you should change your condition.
while ((input = stdIn.readLine()) != null) // Your problem is here
Have you checked if you reach the second while?
Try this in both server and client:
input = stdIn.readLine();
out.println(input);
I am working on small Server/ Client application (console base) in Java. The purpose of the application is to send number from client to server and in the server add (+1) with it and return back to client. Client print the line and send back to server the increased number until it reaches 10.
The connectivity between both classes is working properly, but when I put BufferedReader before PrintWriter in server class, then the application doesn't work and also doesn't throws any error.
Client Code:
int count = 1;
PrintWriter out = null;
BufferedReader in = null;
Socket socket = null;
try {
socket = new Socket("localhost",3700);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
while(in.read() != 10){
out.println(count);
out.flush();
System.out.print(in.read());
};
out.close();
in.close();
socket.close();
Server Code:
ServerSocket serverSocket = null;
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
int count = 1;
try {
serverSocket = new ServerSocket(3700);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
out = new PrintWriter(socket.getOutputStream());
out.println(count);
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(in.read() != 10){
count = in.read();
count++;
};
in.close();
out.close();
serverSocket.close();
socket.close();
while(in.read() != 10){
count = in.read();
count++;
};
You are reading characters and throwing them away, and you are ignoring end of stream. It should be:
int ch;
while((ch = in.read()) !- -1 && ch != 10){
count = ch;
count++;
};
and similarly for the server side. The -1 test is the end of stream condition, which happens when the peer closes the connection.
But more probably you should be using readLine() and Integer.parseInt():
String line;
while ((line = in.readLine()) != null)
{
int value = Integer.parseInt(line);
// etc.
}
In the below code i am just creating a socket to run the Shell command in my App but the problem is some times it runs and most of the time it through the error (libcore.io.IoBridge)
PrintWriter writer = null;
BufferedReader in = null;
String inputLine;
try {
Socket clientSocket = null;
clientSocket = new Socket(LOCAL_ADDRESS, PORT);
Log.d("ExecuteService", (clientSocket.isConnected() ? "Connected" : "Not Connected"));
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true);
writer.println(cmd);
writer.flush();
Log.d("ExecuteService", "Lineis in:" + cmd);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((inputLine = in.readLine()) != null) {
Log.d("ExecuteService", "Lines :" + inputLine);
}
Log.d("ExecuteService", "Lineis out:" + cmd);
writer.close();
writer = null;
in.close();
in = null;
clientSocket.close();
clientSocket = null;
} catch (Exception exception) {
for(StackTraceElement st : exception.getStackTrace())
Log.d("ExecuteService", st.toString());
}
}
Can any one please let me know how n when this error gets occur?
I have the following client socket for sending a string to the server. The server is not getting message. What could be the prob;em?
public void startClient() throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
InetAddress host = null;
BufferedReader stdIn = null;
try {
host = InetAddress.getByName("172.16.2.97");
socket = new Socket(host, 52000);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser = null;
//ClientHelper.unpackISO();
fromUser = ClientHelper.createISO();
if (fromUser != null) {
//System.out.println("Client - " + fromUser);
out.write(fromUser);
System.out.println("Sent message");
}
while ((fromServer = in.readLine()) != null) {
System.out.println("Server - " + fromServer);
if (fromUser != null) {
//System.out.println("Client - " + fromUser);
out.println(fromUser);
}
}
} catch (ISOException ex) {
Logger.getLogger(ClientDemo.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException e) {
System.err.println("Cannot find the host: " + host.getHostName());
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't read/write from the connection: " + e.getMessage());
System.exit(1);
} finally { //Make sure we always clean up
out.close();
in.close();
stdIn.close();
socket.close();
}
}
The method ClientHelper.createISO() return a string which is supposed to be sent to the server. Unfortunately the server is not getting any string. Could the problem be proxy settings. If so how can solve it. Or is it another problem with my code?
What is the problem with my code?
You must flush() the stream after writing to it. Sockets buffer until you get a full packet otherwise
Check the 5th line below, you need to flush your output stream. Otherwise server will not get any packet and you will stuck on your first in.readLine() because its blocking.
fromUser = ClientHelper.createISO();
if (fromUser != null) {
//System.out.println("Client - " + fromUser);
out.write(fromUser);
out.flush(); // FLUSH IT HERE, packet wont be sent until you flush your stream
System.out.println("Sent message");
}
Also add flush after your out.write(fromUser) inside the loop.