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

2 回答 2

2

您的 C 代码需要了解 writeUTF() 写入的数据格式(请参阅 Javadoc),或者更简单地说,您需要在 Java 端使用 write(char[]) 或 write(byte[])。

于 2011-05-20T02:19:30.210 回答
0

这是我解决这个问题的方法:-)

dataOutputStream.write(line.getBytes());

或者更具体地说,这里是我的代码:

out.write(("Hello from " + client.getLocalSocketAddress()).getBytes());
于 2013-11-20T10:29:45.380 回答