我使用的是node.js服务器,我使用Socket.IO聊天示例作为Android的参考。 这是我的app.js文件中的内容
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"]}
答案 0 :(得分:0)
请看下面的链接,它可能对您访问从您的网站发送到Android应用程序的数据有所帮助, http://nkzawa.tumblr.com/post/46850605422/connecting-to-a-socket-io-server-from-android 希望它有所帮助