简体   繁体   中英

Is it possible to simultaneousy read from and write into a java.net.Socket?

Is it possible to simultaneously read and write from a socket? I've a thread which continuously reads a socket. Since only one thread is reading from socket, read operation is thread safe. Now i've many threads (say 100) which write into socket. Hence it is obvious that i've to make write operation thread safe by doing something like this,

package com.mysocketapp.socketmanagement;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketManager {

    private Socket socket = null;

    private InputStream inputStream = null;

    private OutputStream outputStream = null;

    public SocketManager() {
        socket = new Socket("localhost", 5555);
        //server's running on same machine on port 5555
        inputStream = socket.getInputStream();

        outputStream = socket.getOutputStream();
    }

    public void writeMessage(byte[] message) throws IOException {

        synchronized (SocketManager.class) {

            if (message != null) {
                outputStream.write(message);
            }
        }
    }

    public byte[] readMessage() throws IOException {
        byte[] message = new byte[10]; //messages are of fixed size 10 bytes
        inputStream.read(message);
    }
}

Now I have a thread constantly calling readMessage() function (in an while loop). As far as i know if there is no message on the socket to be read the statement inputStream.read(message) will wait for a message.

I want to know whether it is safe to exceute outputStream.write(message); while inputStream.read(message); is in execution

Yes, a socket is bidirectional and enable full duplex communication, there is no problem in doing (on different threads) simultaneous read and write.

And there is no problem in having multiple writing threads. You could synchronize on the socket instance instead of the SocketManager class.

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