简体   繁体   English

是否可以同时读取和写入java.net.Socket?

[英]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. 现在我有许多线程(比如100)写入套接字。 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). 现在我有一个不断调用readMessage()函数的线程(在while循环中)。 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. 据我所知,如果要读取的套接字上没有消息,则语句inputStream.read(message)将等待消息。

I want to know whether it is safe to exceute outputStream.write(message); 我想知道对outputStream.write(message);是否安全outputStream.write(message); while inputStream.read(message); 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. 您可以在套接字实例而不是SocketManager类上进行同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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