标签:连接 输入流 flush input 文本文件 reader socket bre stat
客户端代码:
public class ClientDemo { public static void main(String[] args) throws IOException { //创建客户端Socket对象 Socket s = new Socket("192.168.50.76",11111); //获取输入流,数据来自于键盘录入,直到输入的是886,发送数据结束 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); String line; while ((line=br.readLine())!=null){ if (line.equals("886")){ break; } //发送数据 bw.write(line); bw.newLine(); bw.flush(); } //释放资源 s.close(); } }
服务器端代码:
public class ServerDemo { public static void main(String[] args) throws IOException { //创建客户端Socket对象 ServerSocket ss = new ServerSocket(11111); //监听客户端连接 Socket s = ss.accept(); //接收数据 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //把数据写入文本文件 BufferedWriter bw = new BufferedWriter(new FileWriter("myNet\\bw.txt")); String line; while ((line=br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); } //释放资源 ss.close(); bw.close(); } }
运行结果:
标签:连接 输入流 flush input 文本文件 reader socket bre stat
原文地址:https://www.cnblogs.com/pxy-1999/p/12859727.html