设想如下:
启动服务端--
启动客户端,键入数据,发送--
服务端接收数据,打印出来,键入数据,发送--
客户端接收数据,打印出来,键入数据,发送--
如此无限反复--
public class Server { static BufferedReader br = null; static BufferedWriter bw = null; static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8877); System.out.println("这里是服务端,等待客户端连接"); Socket socket = serverSocket.accept(); System.out.println("已和客户端建立连接"); br = new BufferedReader(new InputStreamReader(socket.getInputStream())); bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); Receiver(); } catch (IOException e) { e.printStackTrace(); } } public static void send() { String info = scanner.nextLine(); try { bw.write(info); bw.flush(); } catch (IOException e) { e.printStackTrace(); } Receiver(); } public static void Receiver() { String info = null; try { while ((info = br.readLine()) != null) { System.out.println(info); } } catch (IOException e) { e.printStackTrace(); } send(); } }
客户端类似,也是一个send()一个receiver()方法,先调用send方法发送然后调用receiver接收,无限循环。
但执行起来在键入数据后却无法发送,按回车发送不出去,怪事。
后来我尝试另一种写法,每次在方法里面创建输入输出流,然后在finally里面关闭
public class Server { static Scanner scanner = new Scanner(System.in); static Socket socket; public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8877); System.out.println("这里是服务端,等待客户端连接"); socket = serverSocket.accept(); System.out.println("已和客户端建立连接"); Receiver(); } catch (IOException e) { e.printStackTrace(); } } public static void send() { String info =scanner.nextLine(); try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); bw.write(info); bw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { socket.shutdownOutput(); } catch (IOException e) { e.printStackTrace(); } Receiver(); } } public static void Receiver() { String info = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); while ((info = br.readLine()) != null) { System.out.println(info); } } catch (IOException e) { e.printStackTrace(); } finally { try { socket.shutdownInput(); } catch (IOException e) { e.printStackTrace(); } send(); } } }
这样能循环一次,但后面就提示流=已经关闭,是不是意味着shutdown输入输出流后就不能重新打开了?
但不关闭的话又会出现和上面一样的情况。
请问大神们这样子到底应该怎么写呢?
相关分类