socket通訊,長度+數據

需求: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();

 

客戶端:

        Socket socket = new Socket("127.0.0.1", 12345);
        OutputStream os = socket.getOutputStream();
        String msgToSend = "{\"type\":-10}";
        byte[] data = msgToSend.getBytes();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeInt(data.length);
        byte[] sendData = msgToSend.getBytes();
        // 發送數據長度(4字節)+數據
        os.write(sendData);
        os.flush();
        InputStream is = socket.getInputStream();
        DataInputStream dis = new DataInputStream(is);
        int lenRead = dis.readInt();
        byte[] recData = new byte[lenRead];
        dis.read(recData);
        System.out.println("收到的數據是:" + new String(recData));
        os.close();
        socket.close();

如果長度爲8個字節,那麼就使用相應的方法,readLong或者writeLong

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章