gpt4 book ai didi

android - Nodejs socket.io 服务器与 Android 连接但不发送消息

转载 作者:行者123 更新时间:2023-11-30 03:48:36 26 4
gpt4 key购买 nike

我正在尝试在 NodeJS 服务器和 Android 之间交换消息。 Android 可以连接并向服务器发送消息,但是服务器发送的消息在 Android 上收不到。

  var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')

app.listen(80);

var text = 'BRUNO';
var text2 = 'BRUNO2';

function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}

res.writeHead(200);
res.end(data);
});
}

var clients = [];

io.sockets.on('connection', function (socket) {
socket.emit('news', text);
socket.emit('news', text2);
socket.send('BRUNO');
socket.on('my other event', function (data) {
console.log(data);
console.log(Math.floor((Math.random()*10000)+1));
});

socket.on('name', function (data) {
socket.set('name',data);
console.log('BRUNOOOO');
if (clients.length ==0 )
clients.push(socket);
else {
socket2 = clients.pop()
socket2.join('room');
socket.join('room');
io.sockets.in('room').emit('news','NOVA SALA');
}
socket.get('name', function (err, data) {
socket.emit('news',data);
});
});
});

安卓

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtTest;
txtTest = (TextView) findViewById(R.id.txtTeste);
try {
ToServer tos = new ToServer(txtTest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public class ToServer implements IOCallback {
private SocketIO socket;
private TextView txtTest;

public ToServer(TextView a) throws Exception {
socket = new SocketIO();
this.txtTest = a;
socket.connect("http://nodebruno.jit.su", this);
socket.emit("my other event", "SERVER RECEBEU ANDROID");
}

@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
txtTest.setText(json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
public void onMessage(String data, IOAcknowledge ack) {
txtTest.setText(data);
Log.d("Event",event );
}

@Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}

@Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}

@Override
public void onConnect() {
System.out.println("Connection established");
}

@Override
public void on(String event, IOAcknowledge ack, Object... args) {
txtTest.setText(event);
Log.d("Event",event );
}
}

在 Android 上我使用这个 https://github.com/Gottox/socket.io-java-client

最佳答案

我试过你的代码,它适用于我的情况。在覆盖功能下,我能够获取从服务器发送的事件和消息。

关于android - Nodejs socket.io 服务器与 Android 连接但不发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14536368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com