TCP通信程序练习3——服务器数据写入文件
客户端代码:
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(); } }
运行结果:
相关推荐
一叶梧桐 2020-10-14
lzzyok 2020-10-10
houjinkai 2020-06-03
zkwgpp 2020-05-04
CloudXli 2020-04-20
Noseparte 2020-03-26
x青年欢乐多 2020-03-02
wangqd 2020-11-09
liupengqwert 2020-10-28
88550291 2020-08-21
yang0cs 2020-07-04
MichelinMessi 2020-06-13
fengshantao 2020-06-11
安得情怀似旧时 2020-06-11
llxxyy0 2020-06-05
Dukezhao 2020-05-29
yshlovelx 2020-05-27