我正在创建一个程序,使用WinSock2将字符串从Java客户端发送到C服务器。我正在使用DataOutputStream通过套接字发送数据。
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.
答案 0 :(得分:1)
你的C代码需要理解writeUTF()编写的数据格式(参见Javadoc),否则你需要在Java端使用write(char [])或write(byte [])。 / p>
答案 1 :(得分:0)
以下是我解决这个问题的方法: - )
dataOutputStream.write(line.getBytes());
或者更具体地说,这是我的代码:
out.write(("Hello from " + client.getLocalSocketAddress()).getBytes());