客户端
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
Socket socket = new Socket("192.168.43.195", 12344);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println(br.readLine());
socket.close();
}
服务端
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket server = new ServerSocket(12344);
Socket socket = server.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String line = "hello";
bw.write(line);
}
代码很简单,可以看到从服务端发出的hello要在客户端输出,但是在运行后并没有达到预期的效果。
除非把server端的输出流关闭才可以在client端输出,在输出流关闭后bw.close()会返回一个null。readline()是一个阻塞函数,在没有数据读的时候会一直卡在那里等待/r/n的出现
分析程序在服务端写入的hello之后客户端则读取,这里选用bufferedreader是因为他里面有一个可以读取整行的方法。调用br.readline()方法之后返回的是string,但是在行的末尾没有/r和/n,readline方法也就没办法停止,一直卡在这里。知道问题出在这里想了一下解决办法,在输入的字符串的末尾加/r/n但是我没有成功,改善的代码如下:
客户端:
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
Socket socket = new Socket("192.168.43.195", 12344);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
System.out.println(br.readLine());
socket.close();
}
服务端:
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(12344);
Socket socket = server.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("hello");
}
可以看到在ps调用的println方法后会自动换行,此时跳到client端当读到hello的末尾会识别到换行符,就可以打印输出了。