需求:socket通讯,传输的数据格式为长度(4个字节)+数据,其中此长度不包含本身的长度
服务端:
ServerSocket ss = new ServerSocket(12345);
Socket s = ss.accept();
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
//读取长度
int lenData = dis.readInt();
byte[] dataByte = new byte[lenData];
dis.read(dataByte);
System.out.println("服务器收到的数据是:"+new String(dataByte));
//往客户端发送数据
String msgToSendStr = "{\"type\":-10,\"msg\":\"我收到数据了\"}";
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
byte[] msgToSend = msgToSendStr.getBytes();
dos.writeInt(msgToSend.length);
dos.write(msgToSend);
os.close();
s.close();
客户端: