root / src / peer / PeerReceiver.java @ 1
History | View | Annotate | Download (2.58 KB)
1 |
package peer; |
---|---|
2 |
|
3 |
import messages.MessageHandler; |
4 |
|
5 |
import javax.net.ssl.SSLServerSocket; |
6 |
import javax.net.ssl.SSLServerSocketFactory; |
7 |
import javax.net.ssl.SSLSocket; |
8 |
import java.io.*; |
9 |
|
10 |
|
11 |
public class PeerReceiver implements Runnable { |
12 |
private SSLServerSocket serverSocket; |
13 |
private int port; |
14 |
|
15 |
PeerReceiver (int port) {
|
16 |
this.port = port;
|
17 |
setJSSE(); |
18 |
setServerSocket(); |
19 |
} |
20 |
|
21 |
/**
|
22 |
* Configures the keystore and truststore
|
23 |
*/
|
24 |
private static void setJSSE() { |
25 |
System.setProperty("javax.net.ssl.keyStore", "src/server.keys"); |
26 |
System.setProperty("javax.net.ssl.keyStorePassword", "123456"); |
27 |
System.setProperty("javax.net.ssl.trustStore", "src/truststore"); |
28 |
System.setProperty("javax.net.ssl.trustStorePassword", "123456"); |
29 |
} |
30 |
|
31 |
/**
|
32 |
* Creates server socket
|
33 |
*/
|
34 |
private void setServerSocket() |
35 |
{ |
36 |
serverSocket = null;
|
37 |
|
38 |
SSLServerSocketFactory serverSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); |
39 |
|
40 |
try {
|
41 |
serverSocket = (SSLServerSocket) serverSocketFactory.createServerSocket(port);
|
42 |
serverSocket.setNeedClientAuth(true);
|
43 |
serverSocket.setEnabledProtocols(serverSocket.getSupportedProtocols()); |
44 |
System.out.println("Server socket thread created and ready to receive"); |
45 |
} catch (IOException e) { |
46 |
System.err.println("Error creating server socket"); |
47 |
e.printStackTrace(); |
48 |
} |
49 |
} |
50 |
|
51 |
@Override
|
52 |
public void run() { |
53 |
Object messageObject = null; |
54 |
SSLSocket connectionSocket = null; |
55 |
|
56 |
while(true) { |
57 |
|
58 |
try {
|
59 |
connectionSocket = (SSLSocket) serverSocket.accept();
|
60 |
} catch (IOException e) { |
61 |
e.printStackTrace(); |
62 |
} |
63 |
|
64 |
ObjectInputStream inFromClient = null; |
65 |
try {
|
66 |
inFromClient = new ObjectInputStream(connectionSocket.getInputStream()); |
67 |
} catch (IOException e) { |
68 |
e.printStackTrace(); |
69 |
} |
70 |
|
71 |
if(connectionSocket != null){ |
72 |
if(inFromClient != null) { |
73 |
try {
|
74 |
messageObject = inFromClient.readObject(); |
75 |
} catch (IOException e) { |
76 |
e.printStackTrace(); |
77 |
} catch (ClassNotFoundException e) { |
78 |
e.printStackTrace(); |
79 |
} |
80 |
|
81 |
MessageHandler mh = new MessageHandler(messageObject);
|
82 |
Peer.executor.submit(mh); |
83 |
} |
84 |
} |
85 |
|
86 |
} |
87 |
} |
88 |
} |