c/c++作为servet,java 为 client
问题1: 在传递整数时,用DataOutputStream中的writeInt(int x)只是传输了一个字节,
下面是一个可以正确通信的例子
public static void main(String []args){
socket = getSocket();
outs = socket.getOutputStream();
dataOuts = new DataOutputStream(outs);
outs = socket.getOutputStream();
dataOuts = new DataOutputStream(outs);
int x = 40023301;
byte []dataByte = toLH(x);
dataOuts.write(dataByte);
byte []dataByte = toLH(x);
dataOuts.write(dataByte);
/*
*
*如果调用 dataOuts.writeInt(x),结果只是传输了一个字节,不知道问什么,所以使用toLH(int n)方法 将int放入byte[]中
*
*/
}
private static Socket getSocket() throws UnknownHostException, IOException {
return new Socket("192.168.2.254", 2005);
}
return new Socket("192.168.2.254", 2005);
}
private static byte[] toLH(int n) {
byte[] b = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) (n >> 8 & 0xff);
b[1] = (byte) (n >> 16 & 0xff);
b[0] = (byte) (n >> 24 & 0xff);
return b;
}
byte[] b = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) (n >> 8 & 0xff);
b[1] = (byte) (n >> 16 & 0xff);
b[0] = (byte) (n >> 24 & 0xff);
return b;
}
问题2:传递字符串的时候,出现的问题与上面一样,使用DataOutputStream中的writeBytes(String s)也是指传输一个字节
下面是一个正确的写法:(部分代码参照 问题1)
.....
String dataString = "this is a test";
byte []dataBytes = dataString .getBytes();
dataOuts.write(dataBytes);
.......