是否可以同时读取和写入java.net.Socket? [英] Is it possible to simultaneousy read from and write into a java.net.Socket?
问题描述
是否可以同时从套接字读取和写入?我有一个连续读取套接字的线程.由于仅从套接字读取一个线程,因此读取操作是线程安全的.现在,我有许多线程(例如100个)写入套接字.因此,很明显,我必须通过执行类似这样的操作来使写操作线程安全,
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);
}
}
现在,我有一个线程不断调用readMessage()函数(在while循环中).据我所知,如果套接字上没有消息要读取,则语句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.
我想知道在执行inputStream.read(message);
时执行outputStream.write(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.
并且具有多个写入线程没有问题.您可以在套接字实例而不是SocketManager类上进行同步.
And there is no problem in having multiple writing threads. You could synchronize on the socket instance instead of the SocketManager class.
这篇关于是否可以同时读取和写入java.net.Socket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!