TCP协议服务端多线程技术
代码
UploadTask. java
1. import java.net.Socket;
2. import java. io. InputStream;
3. import java. io.FileOutputStream;
4. import java. io.File;
5. import java. io.OutputStream;
6.
7. public class UploadTask implements Runnable
8. {
9. private Socket s;
10.
11. public UploadTask(Socket s) {
12. this. s = s;
13. }
14.
15. public void run() {
16.
17. int count = 0;
18.
19. String ip = s.getInetAddress() .getHostAddress() ;
20. System.out.println(ip + ". . . . . .connected") ;
21.
22. try{
23. InputStream in = s.getInputStream() ;
24.
25. File dir = new File("c:\\pic") ;
26. if(!dir.exists() ) {
27. dir.mkdirs() ;
28. }
29. File file = new File(dir, ip + ".bmp") ;
30.
31. //如果文件已经存在于服务端。
32. while(file.exists() ) {
33. file = new File(dir, ip + "(" + (++count) + ") .bmp") ;
34. }
35.
36. FileOutputStream fos = new FileOutputStream(file) ;
37.
38. byte[] buf = new byte[1024] ;
39.
40. int len = 0;
41.
42. while( (len = in.read(buf) ) != -1) {
43. fos.write(buf,0, len) ;
44. }
45.
46. OutputStream out = s.getOutputStream() ;
47.
48. out.write("上传成功".getBytes() ) ;
49.
50. fos. close() ;
51. s. close() ;
52. }catch(Exception e) {
53. e.printStackTrace() ;
54. }
55. }
56. }
复制代码
UploadServerDemo. java
1. import java. io. IOException;
2. import java.net.ServerSocket;
3. import java.net.Socket;
4. import java. io. InputStream;
5. import java. io.File;
6. import java. io.FileOutputStream;
7. import java. io.OutputStream;
8. import java. io.FileNotFoundException;
9. import java. io. IOException;
10.
11. public class UploadPicServer
12. {
13. public static voidmain(String[] args) throws FileNotFoundException, IOException{
14.
15. ServerSocket ss = new ServerSocket(10006) ;
16.
17. while(true) {
18. Socket s = ss.accept() ;
19. new Thread(new UploadTask(s) ) . start() ;
20. }
21.
22. //ss. close() ;
23. }
24. }
复制代码
. .
小欢互联成立于2019年10月,主打海外高性价比云服务器、CDN和虚拟主机服务。近期上线了自营美国CERA机房高速VPS,进行促销活动,为客户奉上美国/香港八折优惠码:Xxc1mtLB优惠码适用于美国CERA一区/二区以及香港一区/二区优惠时间:即日起至10月底优惠码可无限次使用,且续费同价!官网:https://idc.xh-ws.com购买地址:美国CERA一区:https://idc.xh-...
WebHorizon是一家去年成立的国外VPS主机商,印度注册,提供虚拟主机和VPS产品,其中VPS包括OpenVZ和KVM架构,有独立IP也有共享IP,数据中心包括美国、波兰、日本、新加坡等(共享IP主机可选机房更多)。目前商家对日本VPS提供一个8折优惠码,优惠后最低款OpenVZ套餐年付10.56美元起。OpenVZCPU:1core内存:256MB硬盘:5G NVMe流量:200GB/1G...
Digital-VM商家的暑期活动促销,这个商家提供有多个数据中心独立服务器、VPS主机产品。最低配置月付80美元,支持带宽、流量和IP的自定义配置。Digital-VM,是2019年新成立的商家,主要从事日本东京、新加坡、美国洛杉矶、荷兰阿姆斯特丹、西班牙马德里、挪威奥斯陆、丹麦哥本哈根数据中心的KVM架构VPS产品销售,分为大硬盘型(1Gbps带宽端口、分配较大的硬盘)和大带宽型(10Gbps...