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.
Related
I have a Java TCP server, and an android TCP client. I'm trying to send data from client to server. Sending the data seems to be working fine, but the data that is sent, seems corrupted.
Socket connectionSocket = socket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader( connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
System.out.println(clientSentence.split(":")[0]);
if(clientSentence.split(":")[0].equals("packet"))
{
When the server receives the data, the prints show something like this in the console:
packet:user:pass
packet
Which is as expected. But still my if isn't returning true. As if the "packet" string got from socket, is different from the one I type with keyboard in my source. I can't even copy the text from console. When I copy with mouse and paste it somewhere, it only copies the first character.
I use the same structures on client side and send the packet with [DataOutputStream].writeChars(message)
I don't know if it's a different coding of characters that cause this, or something else. Also it's worth noting that when i capture the text with wireshark, the string is something like ".p.a.c.k.e.t"
Thanks.
EDIT: As asked, client side code is something like this:
Socket clientSocket = new socket("127.0.0.1", 1234);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream());
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
String message = "packet:" + username + ":" + password + "\n";
outToServer.writeChars(message);
It's on an android device.
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);
I have client code that looks like:
Socket s = new Socket(server.getHostName(), server.getPort());
PrintWriter p = new PrintWriter(s.getOutputStream());
p.println(message);
p.flush();
s.shutdownOutput();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String newLine;
StringBuffer response = new StringBuffer();
while((newLine = br.readLine()) != null)
response.append(newLine);
System.out.println(response.toString());
p.close();
br.close();
and server code that looks like:
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String nextLine;
StringBuffer request = new StringBuffer();
System.out.println("Starting read....");
String nextline;
while((nextline = br.readLine()) != null){
System.out.println(nextline);
request.append(nextline);
}
System.out.println("Message recived!!");
System.out.println("Request: " + request);
PrintWriter p = new PrintWriter(s.getOutputStream());
p.println("Hello, fileclient!");
System.out.println("Message sent!!");
p.close();
br.close();
Before I put the line s.shutDownInput() the server code would hang at br.readLine(). The way I managed to fix that is to close the PrintWriter some how, either through p.close() or through the current way which doesn't
shutdown the socket like closing the PrintWriter through p.close() does. After that, the interaction between client and server is perfect.
Why does the PrintWriter or the BufferedReader not send/receive until the PrintWriter is closed somehow?
It doesn't have anything to do with PrintWriter. It is an application protocol error on your part.
The server is looping reading lines until end of stream.
The client is sending one line and then not closing the socket, so no end-of-stream got sent (until you added the shutdown).
The server is then responding.
The client is then reading.
So the client doesn't read anything until the server gets out of the loop, and the server doesn't get out of its loop because the client is reading not closing.
So make up your mind. Probably the server should only read one line.
Both sides are behaving exactly as you told them to do. In particular, you instruct the server specifically to read everything the client sends before dispatching any response:
String nextline;
while((nextline = br.readLine()) != null){
System.out.println(nextline);
request.append(nextline);
}
It is important to understand that that will not stop reading until an error or end of stream, where end of stream on a socket corresponds to the other end having been closed and all data having been read. In other words, your server waits for the end of the whole conversation, not the end of a single message, before dispatching a response.
Since that's apparently not what you want, you need to implement a different strategy at the server for determining when to process the data received so far and send a response. If you can be confident that your messages will not contain internal newlines, then that might be as simple as the server performing only one br.readLine() before sending each response.
// Portion of code copied from the senders side
clientSocket = new Socket(successor.IP, successor.PORT);
toServer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String message = "deleteme\n"+predecessor.IP+","+predecessor.PORT;
toServer.write(message);
toServer.newLine();
toServer.flush();
// Portion of code copied from the receivers side
fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toClient = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
input = fromClient.readLine();
On the receivers side there are weird characters before the deleteme. Like the clubs ♣.
I want to know from where do these characters come and how to fix the problem? The temporary fix that I am doing is that before I send the deleteme message I send some garbage data like abcd. Then the deleteme get there as it is.
I'm trying to transfer simple message between PHP socket and JAVA socket. The php socket successfully sends the data and is waiting for Java servers response. But on the other hand Java server's socket is still waiting for the message from PHP.
Here is the Java Code:
ServerSocket s = new ServerSocket(4280);
Socket sock = s.accept();
System.out.println("Connected");
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
System.out.println("Reading");
String str = br.readLine();
System.out.println("Writing");
bw.write(str);
Output:
Connected
Reading
Here's the PHP code:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, "localhost", 4280);
socket_write($socket, "Hello");
echo socket_read($socket, 10);
socket_write($socket, "Lelo");
echo socket_read($socket, 10);
Output:
Browser: waiting for localhost
Two things that can usually cause a problem:
Java is utilizing the readLine() method but your not sending a linefeed and return in your PHP code.
Try also flushing on the PHP side.
Code:
Adding linefeed:
socket_write($socket, "Hello\r\n");
String str = br.readLine(); expect a \n which is not sent by the PHP program.
Add this :
socket_write($socket, "Hello\n" ); // <<<=== '\n' added