1. TCP之客户端读取文本文件服务器控制台输出
(1)客户端:(发送数据到服务端)
1 package cn.itcast_10; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileReader; 6 import java.io.IOException; 7 import java.io.OutputStreamWriter; 8 import java.net.Socket; 9 10 /* 11 * 客户端文本文件,服务器输出到控制台 12 */ 13 public class ClientDemo { 14 public static void main(String[] args) throws IOException { 15 // 创建Socket对象 16 Socket s = new Socket("192.168.12.92", 34567); 17 18 // 封装文本文件 19 BufferedReader br = new BufferedReader(new FileReader( 20 "InetAddressDemo.java")); 21 // 封装通道内的流 22 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( 23 s.getOutputStream())); 24 25 String line = null; 26 while ((line = br.readLine()) != null) { 27 bw.write(line); 28 bw.newLine(); 29 bw.flush(); 30 } 31 32 br.close(); 33 s.close(); 34 } 35 }
(2)服务端:(服务端接收到客户端传过来的数据,显示到控制台)
1 package cn.itcast_10; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.net.ServerSocket; 7 import java.net.Socket; 8 9 public class ServerDemo { 10 public static void main(String[] args) throws IOException { 11 // 创建服务器Socket对象 12 ServerSocket ss = new ServerSocket(34567); 13 14 // 监听客户端连接 15 Socket s = ss.accept(); 16 17 // 封装通道内的流 18 BufferedReader br = new BufferedReader(new InputStreamReader( 19 s.getInputStream())); 20 21 String line = null; 22 while ((line = br.readLine()) != null) { 23 System.out.println(line); 24 } 25 26 27 s.close(); 28 } 29 }