简体   繁体   中英

Alternately sending and receiving byte[] using Socket

I need to send and receive alternately byte [] using Socket. How to do this ? What wrappers to use ? Is this ok or I can do this on quicker way

public boolean SendMessage(byte[] data){
        try{
            socket = new Socket(ipAddress, port);
            OutputStream socketOutputStream = (OutputStream) socket.getOutputStream();
            socketOutputStream.write(data);
            socket.close();
            return true;
        }
        catch(Exception exc){
            System.err.println(exc.getStackTrace());
        }
        return false;
    }

After call of this function I call function for receiving bytes, and again send =>receive and so on. Is there quicker way to do this ?

使用相同的套接字进行读取和写入,只需同步两个应用程序,以便一个读取而另一个写入,反之亦然。

Instead of creating a new socket each time for sending/receiving and then closing it, you should use the same socket.

Say, create two threads. One as the SenderThread and the other as ReceiverThread. The SenderThread creates a socket and then gets the outputstream and you can have a while loop with a flag to indicate whether it should run or not.

Eg: while (running){

The same thing should be done in the ReceiverThread. Create socket and inputstream. Then run the while loop.

In the while loop, you can provide your logic of writing/reading the data to/from the stream.

Use wait and notify so that the threads run in harmony..

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