DataInputStream printing unknown character from a socket - java

I'm getting an unknown character when reading from a socket using DataInputStream. When I send "Hello" on the server side the output is "Hello" the unknown character is the issue. I'm new to socket programming so I don't know what the issue could be. I tried using a BufferReader and PrintWriter too bu the server when using readLine() does not print the text sent but rather java.io.BufferedReader.
Server Side:
//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataInputStream is= new DataInputStream(socket.getInputStream());
String userinput= is.readLine();
System.out.println("Client message: "+userinput);
Client Side:
//BufferedReader std= new BufferedReader(new InputStreamReader(System.in));
String userInput;
DataOutputStream out;
while((userInput=std.readLine()) !=null){
Socket socketClient= new Socket("localhost",5000);
OutputStream os= socketClient.getOutputStream();
out=new DataOutputStream(os);
out.writeUTF(userInput);
out.flush();
socketClient.close();
}

You're using writeUTF on the client side, are you sure readLine on the server side is compatible with it? I had never seen that before, but the javadoc mentions it's a "modified" UTF-8 encoding. Try using readUTF instead, or simply use the regular write method.

If you read a UTF line then you can write UTF or ASCII characters but as opposed to if you read ASCII characters then you must write those characters as ASCII.
try to use out.write(userInput); instead of out.writeUTF(userInput);

Related

How to read unicode characters from server socket

I need to receive a unicode (UTF-8) string sent by client on a server side. The length of the string is of course unknown.
ServerSocket serverSocket = new ServerSocket(567);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
I can read bytes using in.read() (until it returns -1) but the problem is that the string is unicode, in other words, every character is represented by two bytes. So converting the result of read() which would work with normal ascii characters makes no sense.
update
As per suggestions bello, I created the reader as follows:
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"UTF-8"));
I've changed the client side to send a newline (#10#13) after each string.
But the new problem is I get bullshit instead of real string if i call:
in.readLine();
And print the result I get some nonsense string (I cannot even copy it here) although I am not dealing with non-latin chars or anything else.
To see what's going on I introduced following code:
int j = 0
while (j < 255){
j++;
System.out.print(in.read()+", ");
}
So here I just print all bytes received. If I send "ab" I get:
97, 0, 98, 0, 10, 13,
This is what one would expect, but than why the readLine method doesn't produce "good" results?
Anyway, if we couldn't find the actual answer, I should probably collect the bytes (like above) and create my string from them? How to do that?
P.S. Just a quick note - I am on windows.
Use new InputStreamReader(clientSocket.getInputStream(), "UTF-8") in order to set properly the name of the charset to use while reading the InputStream coming from your client
When creating InputStreamReader you can set encoding like this:
BufferedReader in =
new BufferedReader(
new InputStreamReader(clientSocket.getInputStream(), "UTF-8")
);
Try this way:
Reader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream(), StandardCharsets.UTF_8));
Note the StandardCharsets class. It is supported since Java 1.7 and provides more elegant way to specify a standard encoding like UTF-8.

Java socket programming writebytes to readline

I am trying to get a java server and client communicating. For streaming data to the server I have this code:
Socket ClientSocket = null;
ClientSocket = new Socket(IPAddress, portInt);
DataOutputStream outToClient = new DataOutputStream(ClientSocket.getOutputStream());
outToClient.writeBytes(command);
outToClient.flush();
And for the server I have:
ServerSocket mysocket = new ServerSocket(8081);
Socket connectionsocket = mysocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionsocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionsocket.getOutputStream());
//program hangs here, client not sending
GetRequest = inFromClient.readLine();
System.out.println("Received: " + GetRequest);
These are only short portions of the overall code, I have found that the program hangs on the server side when the readLine(); is reached. I am trying to send data with writeBytes(command); where command is a string. Any suggestions? thanks.
writebytes to readline
Stop right there. If you're using readLine() you're using BufferedReader, which is a Reader, which means you should be using a Writer to talk to it, which means you should be using a BufferedWriter, and as you're reading lines you must write lines, which means writing a line terminator (which you aren't presently doing), which means you should use BufferedWriter.newline().
Or PrintWriter.println(), but don't forget to check for errors, as it swallows exceptions.
Don't directly use readLine
Instead try this
If( inFromClient.ready()){
// read string here.
}
It might be possible that buffer is not ready and you are trying to read. So it can create problem.

How to access data in InputStream as String?

I am trying to create an android client and java server application using socket programming. I need to retrieve the file send from java server but i dont want to write that content into another file in client side. Instead i want to create a listbox with the contents in the received file. I can find code for write these contents in a file but I dont know how to access the contents as strings.
Here is the code i tried:
Android client
client=new Socket("10.0.2.2", 7575);
writer=new PrintWriter(client.getOutputStream(),true);
writer.write(mMsg);
writer.flush();
writer.close();
InputStream is=client.getInputStream();
bytesread=is.read(mybytearray,0,mybytearray.length);
I changed my code as follws but it is not working.
InputStream is=client.getInputStream();
BufferedReader bf=new BufferedReader(new InputStreamReader(is));
String value=bf.readLine();
Wrap your inputstream into a BufferedReader
BufferedReader d
= new BufferedReader(new InputStreamReader(is));
and use readLine() method.
Reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), or a carriage return
followed immediately by a linefeed.
Try this:
InputStream is=client.getInputStream();
bytesread=is.read(mybytearray,0,mybytearray.length);
// Create a new String out of the bytes read
String data = new String(mybytearray, 0, bytesread, CharSet);
OR
Wrap the InputStream using BufferedReader and read the data line by line (using readLine()) in String format.
Using buffered reader is best or you can try the code below:
After the last statement use the byte[] "mybytearray" to convert to string as below:
if(bytesread > 0)
String result = new String(mybytearray);

communication with Java server socket via telnet.exe

I'm writting a simple server for experimenting with server socket and telnet.exe
public static void main(String[] args) throws IOException {
String line;
ServerSocket ss = new ServerSocket(5555);
Socket socket = ss.accept();
System.out.println("Waiting for a client...");
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
out.writeUTF("\u001B[2J");
out.writeUTF("Hello client\r\n");
line = in.readUTF();
System.out.println("The dumb client just sent me this line : " + line);
System.out.println("I'm sending it back...");
out.writeUTF(line);
out.flush();
System.out.println("Waiting for the next line...");
System.out.println();
}
Now I'm running this server and connecting to him via telnet.exe. It's ok. But when i'm sending message to server I dont receive this back:
Why it doesnt work?
A telnet client terminates each input-line with a newline. But a DataInputStream does not recognize this as a terminator for input-strings, because a DataInputStream is for binary data.
Wrap your input stream with an InputStreamReader to handle it as a character-based input stream.
Then wrap this one in a BufferedReader. This has the advantage that the input-stream can be filled by the socket in the background while your program executes. It also provides some handy utility methods like the following.
Use the readLine method, which reads data until a newline is found.
Like this:
BufferedReader inputReader = new BufferedReader(new InputStreamReader(in));
[...]
line = inputReader.readLine();
For text-based output of newline-terminated messages back to the client, you should use the output analogue of the BufferedReader, which is the PrintWriter.
DataInput is for reading binary.
From the Javadoc for readUTF()
Reads in a string that has been encoded using a modified UTF-8 format. The general contract of readUTF is that it reads a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String.
First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read. These bytes are then converted to characters by considering them in groups. The length of each group is computed from the value of the first byte of the group. The byte following a group, if any, is the first byte of the next group.
This means the first two byte have to have the length in binary of the following UTF string.
You are typing something like k and j for the first two bytes so the length is something like 25000 bytes, i.e. you haven't typed that much which is why it doesn't return.
What you want instead is to be able to read/write text using classes like BufferedReader and PrintWriter.

Read Special Characters in Socket Server

I am creating Client/Server using Java Networking API. My client will send special unicode characters to Server before and after message. Before message it will send \uc001B and after message \uc00C. After message has been send successfully again client will send \r to server. Server can identify by receiving of this that the message sending is done. But my problem here is how can I check in the server whether the message from client has \r.
DataOutputStream outToServer = new DataOutputStream( clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
outToServer.writeBytes("\uc001B");
outToServer.flush();
outToServer.writeBytes(message.toString());
outToServer.writeBytes("\uc001C");
outToServer.flush();
outToServer.writeBytes("\r");
outToServer.flush();
And here is my server Code to read messages from the client
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter( m_clientSocket.getOutputStream()));
String receivingMessage = "";
while (m_bRunThread) {
String clientCommand = in.readLine().toString();
receivingMessage += clientCommand;
System.out.println("Client Says :" + clientCommand);
if (in.equals("\r")) {
System.out.print("Message Receiving from Client Done : "+ m_clientID);
m_bRunThread = false;
}
}
Thanks
You are using readLine(). It removes the newline, whatever it was: it understands all of them. Ergo you cannot possibly tell what the newline character was. Also you cannot possibly care. Every line you read was terminated by a newline character. But you are on fairly dangerous ground using STX and ETX in association with a Reader. You seem to have a protocol definition problem: you are sending STX/ETX and also expecting newlines. Why?

Categories