使用套接字编程从Java向C发送数据

4

我正在制作一个程序,使用WinSock2从Java客户端向C服务器发送字符串。我正在使用DataOutputStream通过socket发送数据。

C服务器确认接收到了字节,但是当我尝试访问数据时,没有任何内容显示。

服务器

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();
 }

客户端

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

            }

输出

Server: Received 5 bytes, data "" from client
BUFFER :
Server: Echoing the same data back to client...
BUFFER :
Server: send() is OK.
2个回答

2

您的C代码需要理解writeUTF()(请参见Javadoc)编写的数据格式,否则更简单的方法是在Java端使用write(char[])或write(byte[])。


正确!Java 正在发送 16 位 UNICODE x'0048',而 C 程序期望接收 7 位 ASCII(或更可能是某种 8 位 Windows 编码)。printf 将第一个字节 x'00' 解释为字符串结尾。 - James Anderson
1
@James Anderson:不正确。Java正在发送一个两字节长度前缀,后跟以Modified UTF-8格式编码的字符:http://download.oracle.com/javase/6/docs/api/java/io/DataInput.html。*请参阅Javadoc.* - user207421

0

我是这样解决的 :-)

dataOutputStream.write(line.getBytes());

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接