1 package com.ericsson.research.transport.ws.spi;
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 import java.io.IOException;
37 import java.net.InetAddress;
38 import java.net.InetSocketAddress;
39 import java.net.ServerSocket;
40 import java.net.Socket;
41
42 import com.ericsson.research.transport.ws.WSAcceptListener;
43 import com.ericsson.research.transport.ws.WSSecurityContext;
44 import com.ericsson.research.transport.ws.WSServer;
45 import com.ericsson.research.transport.ws.WSURI;
46
47 public class WSServerImpl implements WSServer {
48
49 private String host;
50 private int port;
51 private WSAcceptListener serverListener;
52 private WSSecurityContext securityContext;
53 private ServerSocket acceptSocket;
54 private boolean closing;
55
56 public WSServerImpl(String host, int port, WSAcceptListener serverListener, WSSecurityContext securityContext) throws IOException {
57 this.host = host;
58 this.port = port;
59 this.serverListener = serverListener;
60 this.securityContext = securityContext;
61 bind();
62 }
63
64 private void bind() throws IOException {
65 closing = false;
66 for(int i=0;i<=65000;i++) {
67 try {
68 if (securityContext == null)
69 acceptSocket = new ServerSocket(port, 0, InetAddress.getByName(host));
70 else
71 throw new UnsupportedOperationException();
72
73 new Thread() {
74 public void run() {
75 for(;!closing;) {
76 try {
77 Socket socket = acceptSocket.accept();
78 serverListener.notifyAccept(new WSSocketEndpoint(socket, new WSPrefetcher(securityContext), null));
79 } catch(IOException e) {
80 if(serverListener!=null)
81 serverListener.notifyError(e);
82 }
83 }
84 }
85 }.start();
86 serverListener.notifyReady(this);
87 break;
88 } catch(IOException e) {
89 if(port > 65000)
90 throw e;
91 else
92 port++;
93 }
94 }
95 }
96
97 public WSURI getURI() {
98 String scheme = (securityContext==null ? "ws" : "wss");
99
100 InetSocketAddress inetAddress = getAddress();
101 String host = inetAddress.getAddress().getHostAddress();
102 int port = inetAddress.getPort();
103 String resource = "ws";
104
105 byte[] address = inetAddress.getAddress().getAddress();
106 boolean isv6 = address.length > 4;
107
108 if (isv6)
109 host = "[" + host + "]";
110
111 try {
112 return new WSURI(scheme + "://" + host + ":" + port + "/" + resource);
113 } catch (IllegalArgumentException e) {
114
115 if(serverListener!=null)
116 serverListener.notifyError(e);
117 return null;
118 }
119 }
120
121 public InetSocketAddress getAddress() {
122 return (InetSocketAddress)acceptSocket.getLocalSocketAddress();
123 }
124
125 public void close() {
126 closing = true;
127 try {
128 acceptSocket.close();
129 } catch(IOException e) {
130 if(serverListener!=null)
131 serverListener.notifyError(e);
132 }
133 }
134
135 }