想发送一个udp的报文,这样的结构
struct{
int type;
int version;
char name[20];
}。怎样发送最后那20个字符呀?我这样写的对吗
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
DataOutputStream dos = new DataOutputStream(baos);
try {
dos.writeInt(ProtocolConst.ConnectMessage);
dos.writeInt(version);
dos.writeBytes(name);
dos.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
发送的是baos.toByteArray(),那20个字符不会每次都填满。在server端的接收这样写的rcvByte = new byte[2048];
sPacket = new DatagramPacket(rcvByte, rcvByte.length);
ByteArrayInputStream bais = new ByteArrayInputStream(rcvByte, 0, sPacket.getLength());
DataInputStream dis = new DataInputStream(bais);
Log.d(TAG, "type: " + dis.readInt());
Log.d(TAG, "version: " + dis.readInt());
byte[] buf = new byte[1024];
dis.read(buf, 0, 1024);
Log.d(TAG, "name: " + buf.toString());最后打印出来的name是乱码,请问要怎么处理呢?
struct{
int type;
int version;
char name[20];
}。怎样发送最后那20个字符呀?我这样写的对吗
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
DataOutputStream dos = new DataOutputStream(baos);
try {
dos.writeInt(ProtocolConst.ConnectMessage);
dos.writeInt(version);
dos.writeBytes(name);
dos.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
发送的是baos.toByteArray(),那20个字符不会每次都填满。在server端的接收这样写的rcvByte = new byte[2048];
sPacket = new DatagramPacket(rcvByte, rcvByte.length);
ByteArrayInputStream bais = new ByteArrayInputStream(rcvByte, 0, sPacket.getLength());
DataInputStream dis = new DataInputStream(bais);
Log.d(TAG, "type: " + dis.readInt());
Log.d(TAG, "version: " + dis.readInt());
byte[] buf = new byte[1024];
dis.read(buf, 0, 1024);
Log.d(TAG, "name: " + buf.toString());最后打印出来的name是乱码,请问要怎么处理呢?
struct{
int type;
int version;
char name[20];
}
DataOutputStream dos = new DataOutputStream(baos);
try {
dos.writeInt(ProtocolConst.ConnectMessage);
dos.writeInt(version);
dos.writeBytes(name);
dos.close();
baos.close();
dos.flus();
强制清空缓冲一下嘛,C++中的我也不懂。
那你就应该对每个可变字符串进行填充
一般来说是以双方协商,填充字符空格比较多
可以协商好是前置空格还是后置空格,反正就是想办法把char(20)填满,不要留空