java之多线程解决TCP服务端并发上传

来源:互联网 发布:vscode搭建c环境 编辑:程序博客网 时间:2024/05/22 12:10

示例代码:

/** * TCP服务端利用多线程解决并发上传 * @author 小苏 * */public class TCP_Upload_Concurrent {public static void main(String[] args) {ServerSocket ss = null;try {//创建服务端绑定端口10005ss = new ServerSocket(10005);while(true){Socket s = ss.accept();//每连接一个客户端就创建一个线程new Thread(new ServerThread(s)).start();}} catch (IOException e) {e.printStackTrace();}}}class ServerThread implements Runnable{private Socket s;public ServerThread(Socket s) {this.s = s;}@Overridepublic void run() {int num = 0;FileOutputStream fos = null;try {String ip = s.getInetAddress().getHostAddress();InputStream is = s.getInputStream();byte[] buff = new byte[1024];int len;//给文件重命名File file = new File("F://"+ip+num+".txt");while(file.exists()){file = new File("F://"+ip+"("+(num++)+")"+".txt");}fos = new FileOutputStream(file);while((len = is.read(buff)) != -1){fos.write(buff, 0, len);}OutputStream os = s.getOutputStream();byte[] b = "接收完成".getBytes();os.write(b );} catch (Exception e) {e.printStackTrace();}finally{if(fos != null){try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}}


0 0
原创粉丝点击