我正在尝试创建一个使用 websockets 的 android 应用程序。我使用 Gottox socket.io 作为我的 java socket io 客户端和 node js 作为我的服务器。但是,当我运行我的代码时,我得到一个异常,说io.Socket.socketIOException:在我的 android 应用程序上握手时出错。我已经在下面发布了我的代码(java 和 node js)。我究竟做错了什么?
这是我的java代码(客户端)
package terrible.game.tiktakterrible;
import org.json.JSONException;
import org.json.JSONObject;
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class TikTakTerrible extends Activity {
TextView textView;
SocketIO socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tik_tak_terrible);
textView = (TextView) findViewById(R.id.textView);
try {
connect();
} catch (Exception e) {
e.printStackTrace();
}
}
private void connect() throws Exception
{
socket = new SocketIO("http://localhost:5000/");
socket.connect(new IOCallback() {
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
setText("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
setText("Server said: " + data);
}
@Override
public void onError(SocketIOException socketIOException) {
setText(socketIOException.toString());
socketIOException.printStackTrace();
}
@Override
public void onDisconnect() {
setText("Connection terminated.");
}
@Override
public void onConnect() {
setText("Connection established");
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
setText("Server triggered event '" + event + "'");
}
});
socket.send("Hello Server!");
}
public void setText(String arg)
{
textView.setText(arg);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tik_tak_terrible, menu);
return true;
}
}
这是我的节点 js 服务器
var app = require('http').createServer(),
io = require('socket.io').listen(app),
fs = require('fs');
app.listen(5000);
function handler(req, res)
{
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}
io.sockets.on('connection', function (socket) {
});