我正在尝试创建一个使用websockets的android应用程序。我正在使用Gottox插座。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 Worldn');
}
io.sockets.on('connection', function (socket) {
});
你在哪里运行你的android应用程序?尝试更改
socket = new SocketIO("http://localhost:5000/");
socket = new SocketIO("http://your_pc_ip:5000/");
我想这可能就是问题所在。
public void on(String event, IOAcknowledge ack, Object... args)
{
System.out.println( event );
if ("sensor".equals(event) && args.length > 0)
{
try
{
JSONObject ob = new JSONObject(args[0].toString());
final String mensaje = "Sensor: " + ob.getString("sensor") + " Valor: "+ ob.getString("valor");
new Thread(new Runnable()
{
public void run()
{
handler.post(new Runnable() {
public void run()
{
if(mensaje != null)
{
txt.setText(mensaje);
}
}
});
}
}).start();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}