4

i am making a program that sends a string from a Java client to a C server using WinSock2. I am using DataOutputStream to send the data through the socket.

The C server, acknowledges the bytes received, but when i try accessing the data, nothing is displayed.

SERVER

Socket socket = null;
    DataOutputStream dataOutputStream = null;
    DataInputStream dataInputStream = null;
 try {
  socket = new Socket("10.40.0.86", 2007);
  dataOutputStream = new DataOutputStream(socket.getOutputStream());
  dataInputStream = new DataInputStream(socket.getInputStream());
  //dataOutputStream.writeUTF("How are you doing let us see what is the maximum possible length that can be supported by the protocal");
  String line = "hey";
  dataOutputStream.writeUTF(line);
  dataOutputStream.flush();

  //System.out.println(dataInputStream.readLine());
  System.out.println((String)dataInputStream.readLine().replaceAll("[^0-9]",""));
  //System.out.println(dataInputStream.readInt());
  //System.out.println(dataInputStream.readUTF());
 } catch (UnknownHostException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

CLIENT

if (socket_type != SOCK_DGRAM)
            {
                retval = recv(msgsock, Buffer, sizeof(Buffer), 0);
                printf("Server: Received datagram from %s\n", inet_ntoa(from.sin_addr));

            }

output

Server: Received 5 bytes, data "" from client
BUFFER :
Server: Echoing the same data back to client...
BUFFER :
Server: send() is OK.
dragfyre
  • 452
  • 4
  • 11
user761968
  • 41
  • 1
  • 2

2 Answers2

2

Your C code needs to understand the data format written by writeUTF() (see the Javadoc), or else more simply you need to use write(char[]) or write(byte[]) at the Java end.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Correct! Java is sending 16bit UNICODE x'0048' the C program is expecting 7 bit ASCII (or more likely some 8 bit windows encoding). printf interprets the first byte x'00' as end of string. – James Anderson May 20 '11 at 02:37
  • 1
    @James Anderson: Incorrect. Java is sending a two-byte length prefix followed by the characters in Modified UTF-8 format: http://download.oracle.com/javase/6/docs/api/java/io/DataInput.html. *See the Javadoc.* – user207421 May 20 '11 at 03:05
0

Here is how I solved this :-)

dataOutputStream.write(line.getBytes());

Or to be more specific here is my code:

out.write(("Hello from " + client.getLocalSocketAddress()).getBytes());
Muhammad Farag
  • 426
  • 2
  • 12