TCP通信程序练习6——多线程实现文件上传
Posted pxy-1999
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TCP通信程序练习6——多线程实现文件上传相关的知识,希望对你有一定的参考价值。
客户端代码:
public class ClientDemo { public static void main(String[] args) throws IOException { //创建客户端Scoket对象 Socket s= new Socket("192.168.50.76",44444); //封装文本文件数据 BufferedReader br = new BufferedReader(new FileReader("myNet\\InetAddressDemo.java")); //输出流 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); String line; while ((line = br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); } //使输出终止 s.shutdownOutput(); //客户端接收反馈 BufferedReader brClient = new BufferedReader(new InputStreamReader(s.getInputStream())); String data = brClient.readLine(); System.out.println("服务器的反馈:"+data); //释放资源 s.close(); br.close(); } }
服务器端代码:
public class ServerDemo { public static void main(String[] args) throws IOException { //创建客户端Socket对象 ServerSocket ss = new ServerSocket(44444); //为每一个客户端开启一个线程 while (true) { //监听客户端连接 Socket s = ss.accept(); new Thread(new ServerThread(s)).start(); } } }
实现Runnable接口的SeverThread类:
public class ServerThread implements Runnable{ private Socket s; public ServerThread(Socket s) { this.s=s; } @Override public void run() { //接受数据写入到文件 try { BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //解决名称冲突问题 int count = 0; File file = new File("myNet\\Copy["+count+"].java"); while (file.exists()){ count++; file = new File("myNet\\Copy["+count+"].java"); } BufferedWriter bw = new BufferedWriter(new FileWriter(file)); String line; while ((line=br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); } //给出反馈 BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bwServer.write("文件上传成功"); bwServer.newLine(); bwServer.flush(); }catch (IOException e){ e.printStackTrace(); } } }
运行结果:客户端程序每上传一次文件,服务器都会给出一次反馈
以上是关于TCP通信程序练习6——多线程实现文件上传的主要内容,如果未能解决你的问题,请参考以下文章