?Java Socket???,?????????TCP???????????????????????????,?????????????????,???????????????,??????????:
- ???????:??????,????????????,???????????????????????????,???????,?????????
// ????? public void sendPacket(String data, Socket socket) throws IOException { // ???? int length = data.length(); String header = String.format("d", length); socket.getOutputStream().write(header.getBytes()); socket.getOutputStream().write(data.getBytes()); socket.getOutputStream().flush(); } // ????? public String receivePacket(Socket socket) throws IOException { // ???? InputStream inputStream = socket.getInputStream(); byte[] headerBytes = new byte[4]; inputStream.read(headerBytes); String header = new String(headerBytes); int length = Integer.parseInt(header); // ???? byte[] dataBytes = new byte[length]; inputStream.read(dataBytes); return new String(dataBytes); }
- ???????:?????????????,?????????????????????????????,????????????????????????????????????
// ????? public String receivePacket(Socket socket) throws IOException { InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[MAX_PACKET_LENGTH]; int bytesRead; StringBuilder data = https://www.yisu.com/ask/new StringBuilder();>= MAX_PACKET_LENGTH) { break; } } return data.toString(); }
- ????????:??????,??????(????)??????????????????,???????????????
// ????? public void sendPacket(String data, Socket socket) throws IOException { // ?????????? socket.getOutputStream().write(data.getBytes()); socket.getOutputStream().write("\n".getBytes()); socket.getOutputStream().flush(); } // ????? public String receivePacket(Socket socket) throws IOException { InputStream inputStream = socket.getInputStream(); StringBuilder data = https://www.yisu.com/ask/new StringBuilder();"\n"); if (endIndex != -1) { String packet = data.substring(0, endIndex); data.delete(0, endIndex + 1); return packet; } } return data.toString(); }
???????????Java Socket???????????????,????????????????