Socket网络通信问题
//客户端public class Client {
public static void main(String[] args) throws IOException {
Socket clientSocket = new Socket("localhost", 8889);
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
ps.println("美羊羊,今天晚上有时间吗,来我家我教你java~");
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Server Message:");
while (br.readLine() != null) {
System.out.println(br.readLine());
}
ps.close();
br.close();
clientSocket.close();
}
}
//服务端
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(8889);
Socket clientSocket = socket.accept();
System.out.println("客户端来连接了...");
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client Message:" + '\n' + br.readLine());
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
ps.println("Server Message:" + '\n' + "晚上我有时间,不见不散哦~");
br.close();
ps.close();
socket.close();
}
}
为什么客户端写入必须使用PrintStream流 否则程序将进入线程堵塞,有大佬能解答一下吗 客户端可以不用PrintStream吧{:9_241:},只有创建Socket对象监听时会堵塞,客户端则是直接报错
你发送数据之后应该要执行刷新流的操作
在
ps.println("美羊羊,今天晚上有时间吗,来我家我教你java~");下面
加一句
ps.flush() br.readline 会阻塞吧? 而且读到了再循环里面还会继续阻塞,考虑用 临时变量 接收一下读取到的 在打印
页:
[1]