标签:
1、以下只是简单例子,没有用多线程处理,只能一发一收(由于scan.nextLine()线程会进入等待状态),使用时可以根据具体项目功能进行优化处理
2、以下代码使用了1.8新特性,如果要测试以下代码,java版本不能低于1.8
// 客户端 public static void main(String[] args) { try (Scanner scan = new Scanner(System.in); Socket client = new Socket("127.0.0.1", 8484); PrintWriter writer = new PrintWriter(client.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));) { while (true) { // writer.print(scan.nextLine() + "\n"); // Writer 的 write(scan.nextLine() + "\n");方法 // 注意:由于服务器端是使用readLine,如果是用上面两种方式写入,必须加换行符,否则readLine是读取不到数据的 writer.println(scan.nextLine()); writer.flush(); while (reader.ready()) { System.out.println(reader.readLine()); } } } catch (IOException e) { e.printStackTrace(); } }
// 服务端 public static void main(String[] args) { try (Scanner scan = new Scanner(System.in); ServerSocket server = new ServerSocket(8484); Socket sc = server.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(sc.getInputStream())); PrintWriter writer = new PrintWriter(sc.getOutputStream());) { while (true) { writer.println(scan.nextLine()); writer.flush(); while (reader.ready()) { System.out.println(reader.readLine()); } } } catch (Exception e) { e.printStackTrace(); } }
标签:
原文地址:http://www.cnblogs.com/rgky/p/5452467.html