Skip to content

Commit 26d7be7

Browse files
committed
-improved error handling
-minor changes
1 parent dde2740 commit 26d7be7

8 files changed

Lines changed: 94 additions & 249 deletions

File tree

‎example/ChatClient.java‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import javax.swing.JTextField;
1717

1818
import net.tootallnate.websocket.Draft;
19+
import net.tootallnate.websocket.WebSocket;
1920
import net.tootallnate.websocket.WebSocketClient;
2021
import net.tootallnate.websocket.drafts.Draft_10;
2122
import net.tootallnate.websocket.drafts.Draft_17;
@@ -78,11 +79,7 @@ public ChatClient( String defaultlocation ) {
7879
@Override
7980
public void windowClosing(WindowEvent e) {
8081
if (cc != null) {
81-
try {
8282
cc.close();
83-
} catch (IOException ex) {
84-
ex.printStackTrace();
85-
}
8683
}
8784
dispose();
8885
}
@@ -127,8 +124,8 @@ public void onClose() {
127124
close.setEnabled( false );
128125
}
129126

130-
public void onIOError(IOException ex) {
131-
ta.append("Network problem ...\n"+ex+"\n");
127+
public void onError(Exception ex) {
128+
ta.append("Exception occured ...\n"+ex+"\n");
132129
ta.setCaretPosition( ta.getDocument().getLength() );
133130
ex.printStackTrace();
134131
connect.setEnabled(true);
@@ -156,6 +153,7 @@ public void onIOError(IOException ex) {
156153
}
157154

158155
public static void main(String[] args) {
156+
WebSocket.DEBUG = true;
159157
String location;
160158
if( args.length != 0 ){
161159
location = args[0];

‎example/ChatServer.java‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,6 @@ public void onClientMessage(WebSocket conn, String message) {
4141
System.out.println(conn + ": " + message);
4242
}
4343

44-
public void onError(Throwable ex) {
45-
ex.printStackTrace();
46-
}
47-
4844
public static void main(String[] args) throws IOException {
4945
WebSocket.DEBUG = true;
5046
int port = 8887;
@@ -61,4 +57,9 @@ public static void main(String[] args) throws IOException {
6157
s.sendToAll( in );
6258
}
6359
}
60+
61+
@Override
62+
public void onError( WebSocket conn , Exception ex ) {
63+
ex.printStackTrace();
64+
}
6465
}

‎src/net/tootallnate/websocket/Draft.java‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ public enum HandshakeState{
2727
* The WebSocket protocol expects UTF-8 encoded bytes.
2828
*/
2929
public static final Charset UTF8_CHARSET = Charset.forName ( "UTF-8" );
30+
public static final Charset ASCII_CHARSET = Charset.forName ( "US-ASCII" );
3031

3132
private static final byte[] FLASH_POLICY_REQUEST = "<policy-file-request/>".getBytes( UTF8_CHARSET );
3233

@@ -58,8 +59,8 @@ public static HandshakeBuilder translateHandshakeHttp( byte[] buffer, int readco
5859
int previndex = 0;
5960
int index = findNewLine ( lines , previndex );
6061
if ( index == lines.length )
61-
throw new InvalidHandshakeException("not an http header");;
62-
String line = new String ( lines , previndex , index - previndex );
62+
throw new InvalidHandshakeException("not an http header");
63+
String line = new String ( lines , previndex , index - previndex, ASCII_CHARSET);
6364
String[] firstLineTokens = line.split(" ");
6465
//if( firstLineTokens.length != 3)
6566
String path = firstLineTokens[1];
@@ -132,7 +133,7 @@ else if( ownrole == Role.SERVER ){
132133
bui.append ( "\r\n" );
133134
}
134135
bui.append ( "\r\n" );
135-
byte[] httpheader = bui.toString ().getBytes ( UTF8_CHARSET );
136+
byte[] httpheader = bui.toString ().getBytes ( ASCII_CHARSET );
136137
byte[] content = withcontent ? handshakedata.getContent() : null;
137138
ByteBuffer bytebuffer = ByteBuffer.allocate ( ( content==null ? 0 : content.length ) + httpheader.length );
138139
bytebuffer.put ( httpheader );

‎src/net/tootallnate/websocket/WebSocket.java‎

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,7 @@ public enum Role{
4040
* is binded to. Note that ports under 1024 usually require root permissions.
4141
*/
4242
public static final int DEFAULT_PORT = 80;
43-
/**
44-
* The WebSocket protocol expects UTF-8 encoded bytes.
45-
*/
46-
public final static Charset UTF8_CHARSET = Charset.forName ( "UTF-8" );
43+
4744
/**
4845
* The byte representing CR, or Carriage Return, or \r
4946
*/
@@ -157,7 +154,7 @@ public WebSocket(SocketChannel socketChannel, BlockingQueue<ByteBuffer> bufferQu
157154
* @throws IOException When socket related I/O errors occur.
158155
* @throws NoSuchAlgorithmException
159156
*/
160-
public void handleRead() throws IOException, NoSuchAlgorithmException {
157+
public void handleRead() throws IOException {
161158

162159
int bytesRead = -1;
163160

@@ -169,14 +166,14 @@ public void handleRead() throws IOException, NoSuchAlgorithmException {
169166
close();
170167
}
171168
else if( bytesRead > maxpayloadsize ){
172-
wsl.onError ( new RuntimeException("recived packet to big") );
169+
wsl.onError ( this , new RuntimeException("recived packet to big") );
173170
abort ( "recived packet to big" );
174171
}
175172
else if ( bytesRead > 0) {
176-
if(DEBUG) System.out.println( "got: {" + new String( socketBuffer.array() , 0 , bytesRead ) + "}" );
173+
if(DEBUG) System.out.println( "got("+bytesRead+"): {" + new String( socketBuffer.array() , 0 , bytesRead ) + "}" );
177174
if( !handshakeComplete ){
178175
if(draft.isFlashEdgeCase( socketBuffer.array() , bytesRead )){
179-
channelWrite( ByteBuffer.wrap( wsl.getFlashPolicy( this ).getBytes( UTF8_CHARSET ) ) );
176+
channelWrite( ByteBuffer.wrap( wsl.getFlashPolicy( this ).getBytes( Draft.UTF8_CHARSET ) ) );
180177
return;
181178
}
182179
try{
@@ -264,7 +261,7 @@ else if( curop == Opcode.PONG){
264261
if( currentframe == null){
265262
if( f.isFin () ){
266263
if( f.getOpcode () == Opcode.TEXT ){
267-
wsl.onMessage ( this , new String ( f.getPayloadData () , UTF8_CHARSET ) );
264+
wsl.onMessage ( this , new String ( f.getPayloadData () , Draft.UTF8_CHARSET ) );
268265
}
269266
else if( f.getOpcode () == Opcode.BINARY ){
270267
wsl.onMessage ( this , f.getPayloadData () );
@@ -281,11 +278,11 @@ else if( f.getOpcode() == Opcode.CONTINIOUS ){
281278
try {
282279
currentframe.append ( f );
283280
} catch ( InvalidFrameException e ) {
284-
wsl.onError ( e );
281+
wsl.onError ( this, e );
285282
abort( "invalid frame: " +e.getMessage () );
286283
}
287284
if( f.isFin () ){
288-
wsl.onMessage ( this , new String ( f.getPayloadData () , UTF8_CHARSET ) );
285+
wsl.onMessage ( this , new String ( f.getPayloadData () , Draft.UTF8_CHARSET ) );
289286
currentframe = null;
290287
}
291288
}
@@ -295,11 +292,11 @@ else if( f.getOpcode() == Opcode.CONTINIOUS ){
295292
}
296293

297294
// PUBLIC INSTANCE METHODS /////////////////////////////////////////////////
298-
public void abort( ) throws IOException {
295+
public void abort( ){
299296
abort ( "" );
300297
}
301298

302-
public void abort( String problemmessage ) throws IOException {
299+
public void abort( String problemmessage ) {
303300
if(DEBUG){
304301
System.out.println ( "Aborting: " + problemmessage );
305302
}
@@ -308,13 +305,15 @@ public void abort( String problemmessage ) throws IOException {
308305
/**
309306
* Closes the underlying SocketChannel, and calls the listener's onClose
310307
* event handler.
311-
* @throws IOException When socket related I/O errors occur.
312308
*/
313-
public void close() throws IOException {
309+
public void close() {
314310
//TODO Send HTTP error here in some cases / create abort method
315311
currentframe = null;
316312
handshakerequest = null;
317-
this.socketChannel.close();
313+
try {
314+
this.socketChannel.close();
315+
} catch ( IOException e ) {
316+
}
318317
this.wsl.onClose(this);
319318
}
320319

@@ -393,7 +392,7 @@ public void startHandshake( HandshakeBuilder handshakedata ) throws IOException,
393392
}
394393

395394
private void channelWrite(ByteBuffer buf) throws IOException{
396-
if(DEBUG) System.out.println("write: {"+new String(buf.array())+"}");
395+
if(DEBUG) System.out.println("write("+buf.array().length+"): {"+new String(buf.array())+"}");
397396
//printBytes ( buf , buf.capacity () );
398397
buf.rewind ();
399398
socketChannel.write(buf);

‎src/net/tootallnate/websocket/WebSocketAdapter.java‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,6 @@ public void onOpen( WebSocket conn ) {
2727
public void onClose( WebSocket conn ) {
2828
}
2929

30-
@Override
31-
public void onError( Throwable ex ) {
32-
if(WebSocket.DEBUG)
33-
ex.printStackTrace();
34-
}
35-
3630
@Override
3731
public void onMessage( WebSocket conn , byte[] blob ) {
3832
}
@@ -54,12 +48,13 @@ public void onPong( ) {
5448
* @return An XML String that comforms to Flash's security policy. You MUST
5549
* not include the null char at the end, it is appended automatically.
5650
*/
57-
58-
5951
@Override
6052
public String getFlashPolicy( WebSocket conn ) {
6153
return "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\""
6254
+ conn.getPort() + "\" /></cross-domain-policy>\0";
63-
}
55+
}
6456

57+
@Override
58+
public void onError( WebSocket conn , Exception ex ) {
59+
}
6560
}

‎src/net/tootallnate/websocket/WebSocketClient.java‎

Lines changed: 36 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,18 @@
11
package net.tootallnate.websocket;
22

33
import java.io.IOException;
4+
import java.net.ConnectException;
45
import java.net.InetSocketAddress;
56
import java.net.URI;
67
import java.nio.ByteBuffer;
78
import java.nio.channels.SelectionKey;
89
import java.nio.channels.Selector;
910
import java.nio.channels.SocketChannel;
10-
import java.security.MessageDigest;
11-
import java.security.NoSuchAlgorithmException;
1211
import java.util.Iterator;
13-
import java.util.Random;
1412
import java.util.Set;
1513
import java.util.concurrent.LinkedBlockingQueue;
1614

17-
import net.tootallnate.websocket.WebSocket.Role;
18-
import net.tootallnate.websocket.drafts.*;
15+
import net.tootallnate.websocket.drafts.Draft_10;
1916
import net.tootallnate.websocket.exeptions.InvalidHandshakeException;
2017

2118
/**
@@ -27,7 +24,7 @@
2724
* <var>send</var> method.
2825
* @author Nathan Rajlich
2926
*/
30-
public abstract class WebSocketClient extends WebSocketAdapter implements Runnable {
27+
public abstract class WebSocketClient extends WebSocketAdapter implements Runnable {
3128

3229

3330
// INSTANCE PROPERTIES /////////////////////////////////////////////////////
@@ -55,23 +52,15 @@ public abstract class WebSocketClient extends WebSocketAdapter implements Runnab
5552
* The Draft of the WebSocket protocol the Client is adhering to.
5653
*/
5754
private Draft draft = null;
58-
/**
59-
* Number 1 used in handshake
60-
*/
61-
private int number1 = 0;
62-
/**
63-
* Number 2 used in handshake
64-
*/
65-
private int number2 = 0;
66-
/**
67-
* Key3 used in handshake
68-
*/
69-
private byte[] key3 = null;
7055

7156
// CONSTRUCTORS ////////////////////////////////////////////////////////////
7257
public WebSocketClient(URI serverURI) {
7358
this(serverURI, new Draft_10() );
7459
}
60+
61+
public WebSocketClient( Draft draft , URI serverURI ) {
62+
this(serverURI, draft );
63+
}
7564

7665
/**
7766
* Constructs a WebSocketClient instance and sets it to the connect to the
@@ -117,9 +106,8 @@ public void connect() {
117106
/**
118107
* Calls <var>close</var> on the underlying SocketChannel, which in turn
119108
* closes the socket connection, and ends the client socket thread.
120-
* @throws IOException When socket related I/O errors occur.
121109
*/
122-
public void close() throws IOException
110+
public void close()
123111
{
124112
if (running)
125113
{
@@ -165,9 +153,6 @@ public void releaseAndInitialize()
165153
selector = null;
166154
running = false;
167155
draft = null;
168-
number1 = 0;
169-
number2 = 0;
170-
key3 = null;
171156
}
172157

173158
private boolean tryToConnect(InetSocketAddress remote) {
@@ -190,7 +175,7 @@ private boolean tryToConnect(InetSocketAddress remote) {
190175
}
191176

192177
} catch (IOException ex) {
193-
onIOError(conn, ex);
178+
onError(conn, ex);
194179
return false;
195180
}
196181

@@ -199,7 +184,18 @@ private boolean tryToConnect(InetSocketAddress remote) {
199184

200185
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
201186
public void run() {
202-
running = tryToConnect(new InetSocketAddress(uri.getHost(), getPort()));
187+
try {
188+
running = tryToConnect( new InetSocketAddress( uri.getHost() , getPort() ) );
189+
} catch ( IllegalArgumentException e ) {//
190+
onError(conn, e);
191+
conn.close();
192+
return;
193+
}
194+
catch (SecurityException e) {
195+
onError(conn, e);
196+
conn.close();
197+
return;
198+
}
203199

204200
while (this.running) {
205201
SelectionKey key = null;
@@ -220,16 +216,18 @@ public void run() {
220216
conn.handleRead();
221217
}
222218
}
223-
} catch (IOException ex) {
224-
if( key != null )
225-
key.cancel();
226-
onIOError(conn, ex);
227-
} catch (Exception ex) {
228-
onError( ex );
219+
} catch (InvalidHandshakeException e) {
220+
onError( e );
221+
close();
222+
return;
223+
}
224+
catch (IOException e) {
225+
//if(e instanceof ConnectException == false)
226+
onError( e );
227+
close();
228+
return;
229229
}
230230
}
231-
232-
//System.err.println("WebSocketClient thread ended!");
233231
}
234232

235233
private int getPort() {
@@ -255,12 +253,12 @@ private void sendHandshake() throws IOException, InvalidHandshakeException {
255253
}
256254
int port = getPort();
257255
String host = uri.getHost() + (port != WebSocket.DEFAULT_PORT ? ":" + port : "");
258-
String origin = "x"; // TODO: Make 'origin' configurable
256+
//String origin = "x"; // TODO: Make 'origin' configurable
259257

260258
HandshakedataImpl1 handshake = new HandshakedataImpl1();
261259
handshake.setResourceDescriptor ( path );
262260
handshake.put ( "Host" , host );
263-
handshake.put ( "Origin" , origin );
261+
//handshake.put ( "Origin" , origin );
264262
conn.startHandshake ( handshake );
265263
}
266264

@@ -295,15 +293,15 @@ public void onClose(WebSocket conn)
295293
* Calls subclass' implementation of <var>onIOError</var>.
296294
* @param conn
297295
*/
298-
public void onIOError(WebSocket conn, IOException ex)
296+
public void onError(WebSocket conn, IOException ex)
299297
{
300298
releaseAndInitialize();
301-
onIOError(ex);
299+
onError(ex);
302300
}
303301

304302
// ABTRACT METHODS /////////////////////////////////////////////////////////
305303
public abstract void onMessage(String message);
306304
public abstract void onOpen();
307305
public abstract void onClose();
308-
public abstract void onIOError(IOException ex);
306+
public abstract void onError( Exception ex);
309307
}

0 commit comments

Comments
 (0)