首页 > 代码库 > 网络编程 TCP学习
网络编程 TCP学习
上传txt文本 通过socket向服务端发送数据 然后用serversocket 接收socket 通过流读取数据保存 服务端在发送确认信息并在客户端输出
客户端
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class txtClient { /** * @param args * @throws IOException * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException, IOException { // TODO Auto-generated method stub Socket s = new Socket("10.64.130.51", 10002); BufferedReader br = new BufferedReader(new FileReader("F:\\fd.txt")); PrintWriter pw = new PrintWriter(s.getOutputStream(), true); String str = null; while((str = br.readLine()) != null){ //System.out.println(str); pw.println(str); } pw.println("over"); System.out.println("开始上传"); BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream())); str = brin.readLine(); System.out.println(str); br.close(); s.close(); } }
服务端
import java.io.*; import java.net.*; public class txtServer { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ServerSocket ss = new ServerSocket(10002); Socket s = ss.accept(); BufferedReader brin= new BufferedReader(new InputStreamReader(s.getInputStream())); BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\fd2.txt")); String str = null; System.out.println("接受中"); while((str = brin.readLine()) != null){ System.out.println(str); if(str.compareTo("over") == 0) break; bw.write(str); } //BufferedWriter bwout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); PrintWriter pw = new PrintWriter(s.getOutputStream(), true); pw.println("上传成功"); bw.close(); s.close(); ss.close(); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。