使用socket编程将数据从Java发送到C
我正在制作一个程序,使用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.
# 1 楼答案
您的C代码需要理解writeUTF()编写的数据格式(参见Javadoc),或者更简单地说,您需要在Java端使用write(char[])或write(byte[])