使用套接字编程将数据从Java发送到C.

时间:2011-05-20 00:58:41

标签: java c sockets winsock2 dataoutputstream

我正在创建一个程序,使用WinSock2将字符串从Java客户端发送到C服务器。我正在使用DataOutputStream通过套接字发送数据。

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

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

客户端

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 个答案:

答案 0 :(得分:1)

你的C代码需要理解writeUTF()编写的数据格式(参见Javadoc),否则你需要在Java端使用write(char [])或write(byte [])。 / p>

答案 1 :(得分:0)

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

dataOutputStream.write(line.getBytes());

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

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