socket通信如何封装帧结构
这是文档的一部分,这个文档像密码本一样,但我百度了半天。还是不知道怎么拼接。我**原以为**是这样:(客户端代码)
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 8003);
Scanner in = new Scanner(System.in);
String str = "68H04H00000000H13H"; //发送的字符
byte[] bytes = str.getBytes("UTF-8");//转成bytes
OutputStream os = socket.getOutputStream();
//如果输入q则退出
while (!(in.nextLine()).equals("q")) {
os.write(bytes);
}
os.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
服务端
try {
//封装输入流(接收客户端的流)
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
byte[] bytes = new byte[1]; // 一次读取一个byte
String ret = "";
while (dis.read(bytes) != -1) {
ret += bytes;
}
System.out.println(ret+"\n这是客户端发送的消息");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("client is over");
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是我发现好像不太对。这行代码到底要怎么改。大佬们教教我
String str = "68H04H00000000H13H"; //发送的字符