简体   繁体   中英

Read bytes from socket

I want to read the exact number of bytes(exact length) write to the socket by server. For example if server write "Hello" and next time server write("world"). So I need to capture those two writes as two reads from client socket. I have implemented a server and client as follows to demonstrate my problem. In that example out put is similar to following

1234...89 90........1034 1035......2004

what I expect is 1

2

3

.

.

2004

.

how can I accomplish this.

//server
 ServerSocket server = new ServerSocket(9999);
        Socket s =server.accept();
        InputStream stream = s.getInputStream();
        byte[] by = new byte[1024];

        while(true){
            stream.read(by);
            String received = new String(by, 0, by.length, "ISO8859_1");
            System.out.println(received);
        }


//client
            Socket s = new Socket("localhost", 9999);
            OutputStream out =s.getOutputStream();
            int i =0;
            while(true){
                i++;
                byte[] msg=Integer.toString(i).getBytes();
                out.write(msg);
            }

can some one please help me to do this..

You can't directly with TCP. TCP is a streaming protocol, it doesn't have messages.

You'll need to build your own "protocol" above that. The simplest way is simply to first write the number of bytes the next message will contain, then the message.

On the client side, you first read the message size, then the whole message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM