码迷,mamicode.com
首页 > 编程语言 > 详细

Java中实现多线程Server

时间:2015-07-01 16:07:15      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:java   多线程   server   socket   线程   

首先,我们来看一下单线程的Server如何实现。

指定要监听的端口号,并创建一个ServerSocket对象。当通过accept()方法接受请求后,会返回一个Socket对象。之后我们通过这个这个Socket对象即可与请求方进行通信。这里我们使用了ObjectOutputStream和ObjectInputStream对象实现输入输出流,好处是可以通过序列化传输任何对象。当然,你也可以使用其他输入输出流对象。最后,不要忘记关闭输入输出流和Socket。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server{
 
    public static void main(String[] args) throws IOException, ClassNotFoundException {
         
        int listeningPort = 14837;
        ServerSocket serverSocket = new ServerSocket(listeningPort);   
        Socket clientSocket = serverSocket.accept();
         
        ObjectOutputStream objOut = new ObjectOutputStream(clientSocket.getOutputStream());
        ObjectInputStream objIn = new ObjectInputStream(clientSocket.getInputStream());
         
        // Write your handler here
         
        objIn.close();
        objOut.close();
        clientSocket.close();
        serverSocket.close();
    }
}

 

接下来我们要在此基础上,将其扩展为多线程版本。

我们知道,如果想让一段代码多线程运行,只需新建一个类继承Thread。复写run()方法,把要执行的代码放在该方法内即可。

一个Socket对象就可以确立Server和请求方之间的链接,之后我们只需将clientSocket作为参数传入线程的构造方法即可。之后的处理全部在线程内部实现。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.net.*;
import java.io.*;
 
public class DefaultSocketServer extends Thread {
         
    private Socket clientSocket;
    private ObjectInputStream objIn;
    private ObjectOutputStream objOut;
 
    public DefaultSocketServer(Socket clientSocket){
        this.clientSocket = clientSocket;
    }
 
    public void run(){
        if (openConnection()){
            try {
                handleSession();
                closeSession();
            } catch (ClassNotFoundException | IOException e) {
                e.printStackTrace();
            }          
        }
    }
     
    private boolean openConnection(){
        try {          
            objOut = new ObjectOutputStream(clientSocket.getOutputStream());
            objIn = new ObjectInputStream(clientSocket.getInputStream());          
        } catch (Exception e){
            System.err.println("Unable to obtain stream.");
            return false;
        }
        return true;
    }
 
    private void handleSession() throws IOException, ClassNotFoundException{
        // Write your handler here
    }
     
    private void closeSession() throws IOException{
        objIn.close();
        objOut.close();
        clientSocket.close();
    }
}

 

最后修改Server类。每次accept一个新的请求,就new一个新的线程,将clientSocket作为参数传入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server{
 
    public static void main(String[] args) throws IOException, ClassNotFoundException {
         
        int listeningPort = 14837;
        ServerSocket serverSocket = null;
        serverSocket = new ServerSocket(listeningPort);
         
        while (true) { 
            Socket clientSocket = serverSocket.accept();
            DefaultSocketServer defaultSocketServer = new DefaultSocketServer(clientSocket);
            defaultSocketServer.start();             
        }
    }
}

注:原文转自我的博客《Java中将Socket与Thread结合实现多线程服务器

版权声明:本文为博主原创文章,未经博主允许不得转载。

Java中实现多线程Server

标签:java   多线程   server   socket   线程   

原文地址:http://blog.csdn.net/u014076884/article/details/46710127

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!