用JavaSocket开发高并发小型服务器
一、表示Socket服务端的类:Server.java
Java代码
1public class Server extends Thread{
2 public static int port = 6789;
3 public static String host = "10.60.1.127";
4 private static ServerSocket server = null;
5
6 public void run() {
7 if(server == null){
8 try{
9 //1、新建ServerSocket实例
10 server = new ServerSocket(port);
11 }catch(IOException e){
12 e.printStackTrace();
13 }
14 }
15
16 System.out.println("服务器启动...");
17 while(true){
18 try{
19 //2、访问ServerSocket实例的accept方法取得一个客户端Socket对象
20 Socket client = server.accept();
21 if(client == null) continue;
22
23 new SocketConnection(client, "D:\\").start();
24
25 }catch(IOException ex){
26 ex.printStackTrace();
27 }
28 }
29 }
30
31 public static void main(String[] args) {
32 new Server().start();
33 }
34
35}
Socket客户端处理类:SocketConnection.java
Java代码
36public class SocketConnection extends Thread{
37 private Socket client;
38 private String filepath;
39
40 public SocketConnection(Socket client, String filepath){
41 this.client = client;
42 this.filepath = filepath;
43 }
44
45 public void run(){
46 if(client == null) return;
47
48 DataInputStream in = null;
49 DataOutputStream writer = null;
50
51 try{
52 //3、访问Socket对象的getInputStream方法取得客户端发送过来的数据流
53 in = new DataInputStream(new InputStream()));
54
55 String fileName = in.readUTF(); //取得附带的文件名
56
57免费分享源码大全 if(dsWith("/") == false && dsWith("\\") == false){
58 filepath += "\\";
59 }
60 filepath += fileName;
61
62 //4、将数据流写到文件中
63 writer = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(new File(filepath)))));
64
65 int bufferSize = 2048;
66 byte[] buf = new byte[bufferSize];
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论