首先,我们来看一下单线程的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();
} } } |
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u014076884/article/details/46710127