I'm trying to send a string from my c client to a Java server, after which the server sends a text file to the client.
This is the part of client code that sends the string.
int n = write(sock_fd,"Ready",5);
if (n < 0)
printf("ERROR writing to socket\n");
recv_file(sock_fd, filename);
And this is the server part of java code:
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from client is " + message);
String FILENAME = "data.txt";
sendFile(socket, "data.txt");
Now I have verified that if I remove the part in the server code where it tries to read the string from c client, the rest of the code works fine and the file is transmitted. But if do not comment the string receiving code, both the server and client keep waiting.
I will be grateful if somebody solves this issue for me.
P.S. I know this question has been asked before but that didn't help me, so I started a new thread.
br.readLine() wants to read a line. The client never sends a newline, so the server is waiting for a newline... forever!
Add a newline to the command sent by the client:
int n = write(sock_fd,"Ready\n", 6);
Related
I have developed a small java client that suppose to communicate with a tool installed on unix-server.
I'm working with Socket first time so could do something wrong. I am also limited to Java 6.
In brief code looks like this
I use Socket to establish connection.
Socket socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(endpoint, port);
socket.connect(socketAddress, 5000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Here is how I send message
out.println("Hello");
out.flush();
And here is how I read response
String res = "";
int letter;
while(letter = in.read() != -1) {
char c = (char) letter;
res += c;
}
F.x. If I send a message "Hello", I will receive answers with 2 lines (see example below)
> Hi there
> My name is Robot
The things stuck when I read next character after "Robot\n", I expected that in.read() != -1 will be true and thus it will stop itself, but that is not a case and instead everything just stuck.
What could be the reason to this and how to solve? Thanks.
Please let me know if I need to provide more information.
I had to close my output writer before reading from it, otherwise it blocks.
if (!socket.isOutputShutdown()) {
socket.shutdownOutput();
}
The answer came from a person who later deleted own answer :-/
I am having a little bit of trouble sending and receiving strings from client to server. Assume I have the sockets set up correctly.
This is what I am using to send/receive server side:
fromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
toClient = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String clientInput;
clientInput = fromClient.readLine();
is how my server receives inputs from the client.
Client side same deal:
toServer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
inputLine = bufferedReader.readLine(); //inputLine reads from the console
toServer.write(inputLine);
I can send a message to the sever and it will receive it but when I uncomment out this bit for the client to receive a response from the server:
// serverInput = fromServer.readLine();
//
// System.out.println(serverInput);
It will hang and the server side wont receive the initial message sent. I have no idea whats wrong and I just want to get a reply from the server. Any help is appreciated. Thanks
BufferedReader.readLine() will strip the newline character for you.
That means, at client side, inputLine does not have a trailing \n, which means the client did not send the end of line signal to the server and vice versa.
Client Side
toServer.write(...);
toServer.newLine(); // <--- send new line
toServer.flush(); // <--- flush buffered data
Server should do the similar thing.
I have a simple client/server I'm working on. I have to send the a cookie from the server to the client(it's just a string), but my client won't read the inputStream.
Server:
out = new PrintStream(sock.getOutputStream());
out.println(text);
out.println(temp2State);
out.println(temp2State);
Client:
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String textClient = in.readLine();
String temp1= in.readLine();
String temp2= in.readLine();
This is just the code that seems to be giving me trouble. On the client I receive textClient but then the next 2 are blank. If I do a print out of temp2state on the server before it's sent I get a string, yet if I print out temp1 on the client, its empty. So it's seems to be lost in translation. That being said if use a for loop to receive the data(which was shown in class) it will return temp1 but then textClient is empty. This is being done on a socket so I do have try/catch but it didn't seem relevant.
Alternate input read:
for (int i = 1; i <= 5; i++) {
fromServer = in.readLine();
if (fromServer != null) {
String textClient = in.readLine();
String temp1= in.readLine();
String temp2= in.readLine();
}}
FOUND THE ISSUE:
Turns out I had a string trying to be sent with System.lineSeperator() attached which was sending an empty line.
As per Java API,
public PrintStream(OutputStream out) constructor Creates a new print stream and it will not flush automatically.
Please try the with constructor which accepts true to auto flush, whenever data is written in it.
Please modify your code like
out = new PrintStream(sock.getOutputStream(), true);
I try to communicate with a java application to a µController in wifi (Flyport).
I have a problem with the java application :
It first create a socket to communicate with the Flyport server, then send a message and receive the Flyport answer.
Everything work fine until the read part. I'm polling the read() function of the BufferedReader until it return -1, but it doesn't. The first read works fine, all the answer are red, but the application stay stuck when it tries to read again.
My code is very simple :
Java application :
try (
Socket clientSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
)
{
...//Connection and sending message works fine
}
char[] buffer = new char[500];
while ((in.read(buffer)) != -1) { // first read() works fine, second read() stay stuck...
System.out.println(buffer); // display all answer sent by flyport
}
The code in the flyport :
while(isClientConnected){
//check if client is still connected
...
//read client message
while((RxLen=TCPRxLen(sock))>0)
{
TCPRead(sock,bff,RxLen);
strcat(msg,bff);
}
//write back to the client that the order is received
TCPWrite(sock, msg, strlen(msg));
//process the client order
...
//Write to the client that the process is done
TCPWrite(sock, msg2, strlen(msg2));
}
The java application read msg and msg2 with the first read(). msg and msg2 have "\r\n" at the end.
Doesn't somebody can tell me where I am wrong ?
Is there a function from BufferedReading that tells how much data there is left to read ?
Thanks and regards.
NB : I try with a small buffer in the java application, the problem is the same, read() is stuck when there is nothing left to read...
You're reading from the socket until end of stream, and you're never causing end of stream, as you are never closing the socket at the sender. Either close the socket or don't read until end of stream.
I'm recently learning how to create sockets to connect to a webserver. I've managed to write a little something in Java:
BufferedReader inUser = new BufferedReader(new
InputStreamReader(System.in));
Socket clientSocket = new Socket("www.google.com", 80); // url expected
DataOutputStream outServer = new DataOutputStream
(clientSocket.getOutputStream());
BufferedReader inServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String sentence = inUser.readLine();
outServer.writeBytes(sentence + '\n');
String modifiedSentence = inServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
inUser.close();
outServer.close();
inServer.close();
clientSocket.close();
I'm also using a socketTest program (from http://sockettest.sourceforge.net/) to test my client. The connection seems fine and I can use the sockettest to receive and send back messages (by hosting a local server). When I try to send a string to a webserver (in my java code it's named 'sentence'), it returns bad requests for random input like 'sd' or 'a', as expected. However, when I type the query I wished to receive feedback on, I don't receive anything. To be sure, this is what I put in (stored in 'sentence'):
GET index.html http/1.0
Either I should get the file if it exists or an exception if something went wrong, right? I don't receive anything though. Stranger yet, I've noticed that the first time I give input, I just have to make sure I have 3 separate random strings (separated by space) to have it accepted as valid input. And any random input I enter afterwards, like 'sd' will also be accepted.
Another observation I made is that the program keeps running. Normally I should read a single line then the program stops. This means it wasn't able to read anything.
I'm using port 80 for all the pages I've tried. Here's a small list of websites I've tried to perform a query on:
- www.google.com
- en.wikipedia.org
- www.cracked.com
I've tried a few others setup for the sole purpose of tutorials. Why don't I receive anything? When I tried it with telnet some seemed to work (though www.google.com always returned a xxx error found).
Try writing an additional "\r\n" before flushing the output stream:
BufferedReader inUser = new BufferedReader(new InputStreamReader(System.in));
URL url = new URL("http://www.google.com");
Socket clientSocket = new Socket(url.getHost(), 80); // url expected
OutputStream output = clientSocket.getOutputStream();
PrintWriter pw = new PrintWriter(output,false);
pw.print("GET index.html HTTP/1.0\r\n");
pw.print("\r\n");
pw.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String modifiedSentence = input.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);