简体   繁体   中英

Java server Socket, reading content from DataInputStream

So I have set up a basic client/server connection and I am trying to send a message to one another on connection, I got the client to receive the message from the server, but the server doesn't recieve the clients message. Here is my current code for reading the sent data from the client:

ServerThread.socket = new ServerSocket(5556);
Socket client = ServerThread.socket.accept();
DataInputStream in = new DataInputStream
    (
        new BufferedInputStream(client.getInputStream())
    );
String s = in.readUTF();
System.out.println("Client: " + s);

Using that it doesn't print out anything, Not even just 'Client: '

Here is my code for my client connection, and sending the message. Note: I wrote this part in VB:

client = New TcpClient()
client.Connect("myiphere", 5556)
Dim stream As NetworkStream = client.GetStream()
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Hello server")
stream.Write(sendBytes, 0, sendBytes.Length)

Is there any reason why the data isn't being recieved? Or why it is being delayed? I have tried surronding the Java portion of the code with a try catch block but no error is emitted.

Any help will be appreciated.

UTFs in a DataInputStream are prepended with 0 and the length.

I haven't done much with VB, so I don't know if there are other errors, but try:

 
 
 
  
  stream.Write(0, sendBytes.Length, sendBytes)
 
  

I shouldn't suggest code in a language I don't know. If you want to read it with readUTF, you'll have to send a 0 byte and a byte equal to the length of the string before you send your text bytes.

Edit: You really might not want to use DataInputStream at all, though. It's intended for storing binary streams. If you're receiving text, try this on the Java side:

BufferedReader in = new BufferedReader(
    new InputStreamReader(
        client.getInputStream()
    )
);
String s = in.readLine();

If you're not sending text, just create a BufferedInputStream as you did and read the bytes off of it.

As maybeWeCouldStealAVan pointed out, readUTF expects two bytes indicating how many more bytes of content there are. See http://docs.oracle.com/javase/6/docs/api/java/io/DataInput.html#readUTF () for details.

However, his/her solution using InputStreamReader doesn't work because InputStreamReader is expecting UTF-16 input (two bytes per character), but your VB client is sending ascii. I would suggest making your VB client send UTF-16 if you can (then using maybeWeCouldStealAVan's java code). If you can't do that (sorry, I don't know what encodings VB allows), then just write the extra two bytes needed to make readUTF work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM