1
我正在使用node.js服務器,並使用Socket.IO聊天示例以供Android參考。 下面是在我的app.js文件解析android上的socket.io數據。 (Gottox Socket.IO)
var io = require('socket.io').listen(8080).sockets;
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
這裏是我的HTML。
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
這裏是我的Android代碼。
try {
SocketIO socket = new SocketIO("http://192.168.0.5:8080");
socket.connect(new IOCallback() {
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
Log.e("Server","Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
Log.e("Server","Server said: " + data);
}
@Override
public void onError(SocketIOException socketIOException) {
Log.e("Server",socketIOException.toString());
socketIOException.printStackTrace();
}
@Override
public void onDisconnect() {
Log.e("Server","Connection terminated.");
}
@Override
public void onConnect() {
Log.e("Server","Connection established");
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
Log.e("Server","Server triggered event '" + event + "'");
}
});
socket.send("Hello Server!");
}catch(MalformedURLException e){
}
大多數的代碼工作正常。問題是,從網站方面來說,如果我發送消息,它不會登錄到Android。 我在庫中默認的日誌函數的日誌中收到了這個消息。
12-22 14:30:36.131: I/io.socket(3262): < 5:::{"name":"chat message","args":["sdfg"]}
HY那裏。你能解決你的問題嗎?目前我也面臨同樣的問題,因爲你是。如果你有解決方案,你能幫助我嗎?這將是一個很大的幫助,我真的很感激它。加1的問題http://stackoverflow.com/questions/28270345/node-js-and-websocket-in-android-eclipse – Abstract