Sending data from Java to C using socket programming

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 data through a socket.

Server C confirms the bytes received, but when I try to access 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(); } 

CUSTOMER

 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. 
+4
source share
2 answers

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

+1
source

Here is how I solved it :-)

 dataOutputStream.write(line.getBytes()); 

Or, more specifically, this is my code:

 out.write(("Hello from " + client.getLocalSocketAddress()).getBytes()); 
0
source

All Articles