Java socket: Can't send proper data - java

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.

Related

Trouble sending/receiving strings for client/server

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.

Initial message on Socket connect

trying to connect via TCP to a server using java sockets, the connection gets refused. I'm supposed to send a key to authenticate. code:
Socket clientSocket = new Socket();
clientSocket.connect(new InetSocketAddress("server.address.whatever", 123456));
System.out.println("Connected");
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String key = "key";
outToServer.writeBytes(key + "\r\n");
String response = inFromServer.readLine();
System.out.println("FROM SERVER: " + response);
clientSocket.close();
It never makes it to the point where it tries to print out "Connected", it throws
java.net.ConnectException: Connection refused
So i never send the key. What am i missing here? How can i send an initial message during connecting? Am i even supposed to do that?
It sounds like there is no server process listening on that socket. Check whether you can make a connection with a tool like nmap (or just telnet).

Why am i getting weird character in socket inputstream

// 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.

Basic PUT, GET request from http server

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

Java readline() keeping socket open

I am trying to have my client connect to my server, and depending on the command send some string back to the client. Currently the app connects and can send strings to the server very nicely. However when I send the command which instructs the server to send something back it hangs. I found that the problem occurs when the client attempts to read the line send from the server.
Server
PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
out.println("GETDATA" + "\n");
out.flush();
out.close();
Client
BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
incomingLine = fromServer.readLine();
Log.d("HERE", "NOT " + incomingLine);
fromServer.close();
Thanks!
I made effectively this same mistake when I was first doing sockets as well.
Don't use PrintWriter with BufferedReader. They're incompatible. By comments, PrintWriter actually hides critical exceptions, so they shouldn't be used in networking. Instead, use a DataInputStream and DataOutputStream for communications.
client = new Socket(hostname, port);
inStr = new DataInputStream(client.getInputStream());
outStr = new DataOutputStream(client.getOutputStream());
Then, send and receive using writeUTF and readUTF, like so:
public void send(String data) throws IOException {
outStr.writeUTF(data); outStr.flush();
}
public String recv() throws IOException {return inStr.readUTF();}
The reason has to do with the UTF encoding; a BufferedReader expects a certain string encoding, which PrintWriter does not give. Thus, the read/write hangs.
The method readLine() expects an end of line character "\n" maybe that's your problem

Categories

Resources