tcp文件上传--多个客户端
1.client
public static void main(String[] args) throws IOException { // 创建客户端Socket对象 Socket s = new Socket("192.168.12.92", 11111); // 封装文本文件 // BufferedReader br = new BufferedReader(new FileReader( // "InetAddressDemo.java")); BufferedReader br = new BufferedReader(new FileReader( "ReceiveDemo.java")); // 封装通道内流 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( s.getOutputStream())); String line = null; while ((line = br.readLine()) != null) { // 阻塞 bw.write(line); bw.newLine(); bw.flush(); } // Socket提供了一个终止,它会通知服务器你别等了,我没有数据过来了 s.shutdownOutput(); // 接收反馈 BufferedReader brClient = new BufferedReader(new InputStreamReader( s.getInputStream())); String client = brClient.readLine(); // 阻塞 System.out.println(client); // 释放资源 br.close(); s.close(); }
2.server
public static void main(String[] args) throws IOException { // 创建服务器Socket对象 ServerSocket ss = new ServerSocket(11111); while (true) { Socket s = ss.accept(); new Thread(new UserThread(s)).start(); } }
3.UserThread
public class UserThread implements Runnable { private Socket s; public UserThread(Socket s) { this.s = s; } @Override public void run() { try { // 封装通道内的流 BufferedReader br = new BufferedReader(new InputStreamReader( s.getInputStream())); // 封装文本文件 // BufferedWriter bw = new BufferedWriter(new // FileWriter("Copy.java")); // 为了防止名称冲突 String newName = System.currentTimeMillis() + ".java"; BufferedWriter bw = new BufferedWriter(new FileWriter(newName)); String line = null; 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(); // 释放资源 bw.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } } }