我正在开发一个Android应用程序,它与Web服务器通信并需要来自服务器的推送通知。
此应用程序成功运行,正如预期的那样,Tornado 2.1作为Web服务器并在Android客户端应用程序中使用weberknecht websockets。
但是,对于Tornado 3.1,当我尝试调用“websocket.connect()”方法时,同一个应用程序总是返回异常。
连接失败:未知状态代码426 导致WebSocketException(id = 830032153816)
我在stackoverflow上读到weberknecht可能与最新的Tornado 3.1不兼容。因此,我搬到了Autobahn网络套接字。但是如果我导入autobahn websocket jar,应用程序会在“connect”方法崩溃。我也尝试过jwebsocket客户端。我也面临同样的问题。
我在代码中遗漏了什么? weberknecht与Tornado 3.1不兼容吗?使用Tornado 3.1有哪些替代方案?或者我应该继续使用Tornado 2.1吗?
public class MainActivity extends Activity {
protected static final String TAG = null;
BaseTokenClient btc;
Toast testToast;
private WebSocketConnection websocket;
URI url;
private class AsyncThread extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
websocket.connect();
} catch (de.roderick.weberknecht.WebSocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = null;
try {
url = new URI("ws://192.168.1.130:8888/ws");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
websocket = new WebSocketConnection(url);
} catch (de.roderick.weberknecht.WebSocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Register Event Handlers
websocket.setEventHandler(new WebSocketEventHandler() {
public void onOpen()
{
Log.e(TAG, "--open");
try {
websocket.send("HELLO");
} catch (de.roderick.weberknecht.WebSocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onMessage(WebSocketMessage message)
{
Log.e(TAG, "--received message: " + message.getText());
System.out.println(message.getText());
}
public void onClose()
{
Log.e(TAG, "--close");
}
});
new AsyncThread().execute();
}
}
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection'
self.write_message("Hello World")
def on_message(self, message):
print 'message received %s' % message
def on_close(self):
print 'connection closed'
application = tornado.web.Application([
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()