我有一个线程从缓冲读取器读取字符(从套接字创建,如下所示):
inputStream = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
这段代码只能运行一次。例如,如果客户端连接并发送以下内容:
“这是一个测试”和“这是另一个测试”,主机输出是:
Reading from stream:
Chars read from stream: 16
This is a test
Reading from stream:
请注意,程序不会收到“这是另一个测试”,因为它停留在读取流上。有没有办法在不减少缓冲区大小的情况下处理这个问题?
这是线程的代码:
public void run() {
boolean dataRecieved = false;
char[] inputChars = new char[1024];
int charsRead = 0;
while (!stopNow) {
try {
Thread.sleep(getDataDelay);
//Read 1024 characters. Note: This will pause the thread when stream is empty.
System.out.println("Reading from stream:");
charsRead = inputStream.read(inputChars); //<< THIS LINE IS PAUSING THE THREAD!>
if ((charsRead = inputStream.read(inputChars)) != -1)
{
System.out.println("Chars read from stream: " + charsRead);
System.out.println(inputChars);
System.out.flush();
}
} catch (IOException e) {
System.out.println("IOException");
//TODO: CLIENT HAS DISCONNECTED...
} catch (InterruptedException e) {
System.out.println("Interrupted");
// Sleep was interrupted.
}
}
}
客户端/发送者的代码(不是我的代码):
public static void main(String[] args) throws IOException {
// <<<<<<<<<<< CLIENT >>>>>>>>>>>>>>>
Socket sock = new Socket("127.0.0.1", 3000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Start the chitchat, type and press Enter key");
String receiveMessage, sendMessage;
while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
System.out.flush(); // flush the data
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
}
}
java.io.InputStream.read()
is a blocking调用,这意味着如果没有可用数据,线程将暂停,直到数据可用。
对于非阻塞 I/O,请使用以下类java.nio
包裹。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)