关于socket中read方法阻塞问题
话不多说上代码-_-
客户端代码
package com.demo.test3;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1", 9527);
BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream());
out.write("hello\n".getBytes());
out.flush();
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
in.readAllBytes();
}
}
服务端代码
package com.demo.test3;
import java.io.BufferedInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(9527);
Socket s = server.accept();
BufferedInputStream sysIn = new BufferedInputStream(s.getInputStream());
List<Character> res = new ArrayList<>();
int ch;
while ((ch = sysIn.read()) != '\n') {
if (ch == -1)
return;
res.add((char) ch);
}
System.out.println(res);
}
}