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. }
复制代码
. .
spinservers怎么样?spinservers大硬盘服务器。Spinservers刚刚在美国圣何塞机房补货120台独立服务器,CPU都是双E5系列,64-512GB DDR4内存,超大SSD或NVMe存储,数量有限,机器都是预部署好的,下单即可上架,无需人工干预,有需要的朋友抓紧下单哦。Spinservers是Majestic Hosting Solutions,LLC旗下站点,主营美国独立...
GreenCloudVPS最近在新加坡DC2节点上了新机器,Dual Xeon Silver 4216 CPU,DDR4内存,10Gbps网络端口,推出了几款大硬盘VPS套餐,基于KVM架构,500GB磁盘起年付30美元。除了大硬盘套餐外,还加推了几款采用NVMe硬盘的常规套餐,最低年付20美元。不过需要提醒的是,机房非直连中国,尤其是电信用户ping值感人,包括新加坡DC1也是如此。大硬盘VPS...
近日Friendhosting发布了最新的消息,新上线了美国迈阿密的云产品,之前的夏季优惠活动还在进行中,全场一次性45折优惠,最高可购买半年,超过半年优惠力度就不高了,Friendhosting商家的优势就是100Mbps带宽不限流量,有需要的朋友可以尝试一下。Friendhosting怎么样?Friendhosting服务器好不好?Friendhosting服务器值不值得购买?Friendho...