how to send an array of bytes over a TCP connection (java programming)

前端 未结 9 1750
粉色の甜心
粉色の甜心 2020-12-13 14:45

Can somebody demonstrate how to send an array of bytes over a TCP connection from a sender program to a receiver program in Java.

byte[] myByteArray
<         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 15:05

    Here is an example that streams 100 byte wav file frames at a time.

    private Socket socket;
    
    public void streamWav(byte[] myByteArray, int start, int len) throws IOException {
    
        Path path = Paths.get("path/to/file.wav");
    
        byte[] data = Files.readAllBytes(path);
    
        OutputStream out = socket.getOutputStream();
        DataOutputStream os = new DataOutputStream(out);
    
        os.writeInt(len);
        if (len > 0) {
            os.write(data, start, len);
        }
    }
    
    public void readWav() throws IOException {
    
        InputStream in = socket.getInputStream();
    
        int frameLength = 100; // use useful number of bytes
    
        int input;
        boolean active = true;
    
        while(active) {
            byte[] frame = new byte[frameLength];
            for(int i=0; i

提交回复
热议问题