Skip to content

Commit 3abf448

Browse files
author
Animesh Kumar
committedFeb 12, 2011
Added some exception handling
1 parent 5116ff5 commit 3abf448

File tree

3 files changed

+97
-58
lines changed

3 files changed

+97
-58
lines changed
 

‎assets/www/js/websocket.js

+25-8
Original file line numberDiff line numberDiff line change
@@ -31,16 +31,14 @@
3131

3232
// WebSocket Object. All listener methods are cleaned up!
3333
var WebSocket = global.WebSocket = function(url) {
34-
// must be overloaded
35-
this.onopen = null;
36-
this.onmessage = null;
37-
this.onclose = null;
38-
this.onerror = null;
39-
4034
// get a new websocket object from factory (check com.strumsoft.websocket.WebSocketFactory.java)
4135
this.socket = WebSocketFactory.getInstance(url);
4236
// store in registry
43-
WebSocket.store[this.socket.getId()] = this;
37+
if(this.socket) {
38+
WebSocket.store[this.socket.getId()] = this;
39+
} else {
40+
throw new Error('websocket instantiation failed! Address could be wrong.');
41+
}
4442
};
4543

4644
// storage to hold websocket object for later invokation of event methods
@@ -63,6 +61,7 @@
6361
WebSocket.store[evt._target]['onerror'].call(global, evt._data);
6462
}
6563

64+
// instance event methods
6665
WebSocket.prototype.send = function(data) {
6766
this.socket.send(data);
6867
}
@@ -74,5 +73,23 @@
7473
WebSocket.prototype.getReadyState = function() {
7574
this.socket.getReadyState();
7675
}
77-
76+
///////////// Must be overloaded
77+
WebSocket.prototype.onopen = function(){
78+
throw new Error('onopen not implemented.');
79+
};
80+
81+
// alerts message pushed from server
82+
WebSocket.prototype.onmessage = function(msg){
83+
throw new Error('onmessage not implemented.');
84+
};
85+
86+
// alerts message pushed from server
87+
WebSocket.prototype.onerror = function(msg){
88+
throw new Error('onerror not implemented.');
89+
};
90+
91+
// alert close event
92+
WebSocket.prototype.onclose = function(){
93+
throw new Error('onclose not implemented.');
94+
};
7895
})();

‎src/com/strumsoft/websocket/phonegap/WebSocket.java

+55-43
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
import java.util.concurrent.BlockingQueue;
4545
import java.util.concurrent.LinkedBlockingQueue;
4646

47+
import android.util.Log;
4748
import android.webkit.WebView;
4849

4950
/**
@@ -247,17 +248,42 @@ protected WebSocket(WebView appView, URI uri, Draft draft, String id) {
247248
// //////////////////////////////////////////////////////////////////////////////////////
248249
/**
249250
* Starts a new Thread and connects to server
251+
*
252+
* @throws IOException
250253
*/
251-
public void connect() {
254+
public Thread connect() throws IOException {
252255
this.running = true;
253-
(new Thread(this)).start();
256+
this.readyState = WEBSOCKET_STATE_CONNECTING;
257+
// open socket
258+
socketChannel = SocketChannel.open();
259+
socketChannel.configureBlocking(false);
260+
// set address
261+
socketChannel.connect(new InetSocketAddress(uri.getHost(), port));
262+
// start a thread to make connection
263+
264+
// More info:
265+
// http://groups.google.com/group/android-developers/browse_thread/thread/45a8b53e9bf60d82
266+
// http://stackoverflow.com/questions/2879455/android-2-2-and-bad-address-family-on-socket-connect
267+
System.setProperty("java.net.preferIPv4Stack", "true");
268+
System.setProperty("java.net.preferIPv6Addresses", "false");
269+
270+
selector = Selector.open();
271+
socketChannel.register(selector, SelectionKey.OP_CONNECT);
272+
Log.v("websocket", "Starting a new thread to manage data reading/writing");
273+
274+
Thread th = new Thread(this);
275+
th.start();
276+
// return thread object for explicit closing, if needed
277+
return th;
254278
}
255279

256280
public void run() {
257-
try {
258-
_connect();
259-
} catch (IOException e) {
260-
this.onError(e);
281+
while (this.running) {
282+
try {
283+
_connect();
284+
} catch (IOException e) {
285+
this.onError(e);
286+
}
261287
}
262288
}
263289

@@ -266,7 +292,7 @@ public void run() {
266292
*/
267293
public void close() {
268294
this.readyState = WebSocket.WEBSOCKET_STATE_CLOSING;
269-
295+
270296
// close socket channel
271297
try {
272298
this.socketChannel.close();
@@ -275,10 +301,10 @@ public void close() {
275301
}
276302
this.running = false;
277303
selector.wakeup();
278-
304+
279305
// fire onClose method
280306
this.onClose();
281-
307+
282308
this.readyState = WebSocket.WEBSOCKET_STATE_CLOSED;
283309
}
284310

@@ -290,7 +316,7 @@ public void close() {
290316
*/
291317
public void send(String text) {
292318
try {
293-
if(this.readyState == WEBSOCKET_STATE_OPEN){
319+
if (this.readyState == WEBSOCKET_STATE_OPEN) {
294320
_send(text);
295321
} else {
296322
this.onError(new NotYetConnectedException());
@@ -390,45 +416,31 @@ private boolean _send(String text) throws IOException {
390416

391417
// actual connection logic
392418
private void _connect() throws IOException {
393-
this.readyState = WEBSOCKET_STATE_CONNECTING;
394-
socketChannel = SocketChannel.open();
395-
socketChannel.configureBlocking(false);
396-
socketChannel.connect(new InetSocketAddress(uri.getHost(), port));
397-
398-
// More info:
399-
// http://groups.google.com/group/android-developers/browse_thread/thread/45a8b53e9bf60d82
400-
// http://stackoverflow.com/questions/2879455/android-2-2-and-bad-address-family-on-socket-connect
401-
System.setProperty("java.net.preferIPv4Stack", "true");
402-
System.setProperty("java.net.preferIPv6Addresses", "false");
419+
// Continuous loop that is only supposed to end when "close" is called.
403420

404-
selector = Selector.open();
405-
socketChannel.register(selector, SelectionKey.OP_CONNECT);
421+
selector.select();
422+
Set<SelectionKey> keys = selector.selectedKeys();
423+
Iterator<SelectionKey> i = keys.iterator();
406424

407-
// Continuous loop that is only supposed to end when "close" is called.
408-
while (this.running) {
409-
selector.select();
410-
Set<SelectionKey> keys = selector.selectedKeys();
411-
Iterator<SelectionKey> i = keys.iterator();
412-
413-
while (i.hasNext()) {
414-
SelectionKey key = i.next();
415-
i.remove();
416-
if (key.isConnectable()) {
417-
if (socketChannel.isConnectionPending()) {
418-
socketChannel.finishConnect();
419-
}
420-
socketChannel.register(selector, SelectionKey.OP_READ);
421-
_writeHandshake();
425+
while (i.hasNext()) {
426+
SelectionKey key = i.next();
427+
i.remove();
428+
if (key.isConnectable()) {
429+
if (socketChannel.isConnectionPending()) {
430+
socketChannel.finishConnect();
422431
}
423-
if (key.isReadable()) {
424-
try {
425-
_read();
426-
} catch (NoSuchAlgorithmException nsa) {
427-
this.onError(nsa);
428-
}
432+
socketChannel.register(selector, SelectionKey.OP_READ);
433+
_writeHandshake();
434+
}
435+
if (key.isReadable()) {
436+
try {
437+
_read();
438+
} catch (NoSuchAlgorithmException nsa) {
439+
this.onError(nsa);
429440
}
430441
}
431442
}
443+
432444
}
433445

434446
private void _writeHandshake() throws IOException {

‎src/com/strumsoft/websocket/phonegap/WebSocketFactory.java

+17-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/*
22
* Copyright (c) 2010 Animesh Kumar (https://github.com/anismiles)
33
* Copyright (c) 2010 Strumsoft (https://strumsoft.com)
4-
*
4+
*
55
* Permission is hereby granted, free of charge, to any person
66
* obtaining a copy of this software and associated documentation
77
* files (the "Software"), to deal in the Software without
@@ -27,7 +27,6 @@
2727
package com.strumsoft.phonegap.websocket;
2828

2929
import java.net.URI;
30-
import java.net.URISyntaxException;
3130
import java.util.Random;
3231

3332
import android.webkit.WebView;
@@ -54,14 +53,25 @@ public WebSocketFactory(WebView appView) {
5453
this.appView = appView;
5554
}
5655

57-
public WebSocket getInstance(String url) throws URISyntaxException {
56+
public WebSocket getInstance(String url) {
57+
// use Draft75 by default
5858
return getInstance(url, WebSocket.Draft.DRAFT75);
5959
}
6060

61-
public WebSocket getInstance(String url, WebSocket.Draft draft) throws URISyntaxException {
62-
WebSocket socket = new WebSocket(appView, new URI(url), draft, getRandonUniqueId());
63-
socket.connect();
64-
return socket;
61+
public WebSocket getInstance(String url, WebSocket.Draft draft) {
62+
WebSocket socket = null;
63+
Thread th = null;
64+
try {
65+
socket = new WebSocket(appView, new URI(url), draft, getRandonUniqueId());
66+
th = socket.connect();
67+
return socket;
68+
} catch (Exception e) {
69+
//Log.v("websocket", e.toString());
70+
if(th != null) {
71+
th.interrupt();
72+
}
73+
}
74+
return null;
6575
}
6676

6777
/**

0 commit comments

Comments
 (0)
Failed to load comments.