Java服务端多线程技术

服务端多线程技术

 

客户端:UploadPicClent.java

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class UploadPicClent {
   public static void main(String[] args) throws IOException {
      System.out.println("客户端启动.........");
      Socket socket = new Socket(InetAddress.getLocalHost(), 45678);
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\clent.rmvb"));
      byte buf[] = new byte[1024];
      int len = 0;
      OutputStream out = socket.getOutputStream();
      while ((len = bis.read(buf)) != -1) {
        out.write(buf, 0, len);
        out.flush();
      }
      socket.shutdownOutput();
      BufferedReader bufr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      String line = bufr.readLine();
      System.out.println(line);
      socket.close();
      bis.close();
   }
}

服务端:UploadPicServer1.java

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

class UploadPicServer1 {
   public static void main(String[] args) throws Exception {
      System.out.println("服务端开启.........");
      ServerSocket ss = new ServerSocket(45678);
      while (true) {
        Socket socket = ss.accept();
        new Thread(new UploadTask(socket)).start();
      }
   }
}

class UploadTask implements Runnable {
   private Socket socket;

UploadTask(Socket socket) {
      this.socket = socket;
   }

   public void run() {
      int count = 0;
      try {
        InputStream in = socket.getInputStream();
        File dir = new File("C:\\rmvb");
        if (!dir.exists())
           dir.mkdirs();
        String ip = socket.getInetAddress().getHostAddress();
        System.out.println(ip + "......connected");
        File file = new File(dir, ip + ".rmvb");
        while (file.exists())
           file = new File(dir, ip + "(" + (++count) + ").rmvb");
        FileOutputStream fos = new FileOutputStream(file);
        byte buf[] = new byte[1024];
        int len = 0;
        while ((len = in.read(buf)) != -1) {
           fos.write(buf, 0, len);
           fos.flush();
        }
        OutputStream out = socket.getOutputStream();
        out.write("上传成功".getBytes());
        fos.close();
        socket.close();
      } catch (Exception e) {
      }
   }
}