我尝试使用Xamarin和nodeJs服务器通过Android应用程序测试websocket。我有一个socket.emit请求的速度问题:它非常慢(大约20秒,这是按钮点击和我在nodejs控制台上看到“console.log(data)”的那一刻之间的延迟)。但是,socket.on可以快速接收数据。我不知道为什么。 我知道我的代码是非常基础的,但只是看看websocket是如何工作的。
Android应用
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Quobject.SocketIoClientDotNet.Client;
namespace TestWebSocket
{
[Activity(Label = "TestWebSocket", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
private Socket socket;
private EditText textEnvoi;
private EditText textReponse;
private Button button;
private string dataSend;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
button = FindViewById<Button>(Resource.Id.MyButton);
textEnvoi = FindViewById<EditText>(Resource.Id.sendText);
textReponse = FindViewById<EditText>(Resource.Id.reponseText);
button.Click += delegate {
socket = IO.Socket("http://192.168.1.xx:8080/");
dataSend = textEnvoi.Text;
socket.Emit("txt", dataSend);
socket.On("dataReceive", data =>
{
//textReponse.Text = data.ToString();
Console.WriteLine("Texte : {0}", data.ToString());
}
);
};
}
}
}
NodeJs代码
var http = require('http');
// Chargement du fichier index.html affiché au client
var server = http.createServer(function(req, res) {
res.writeHead(200);
res.end("content");
});
// Chargement de socket.io
var io = require('socket.io').listen(server);
// Quand un client se connecte, on le note dans la console
io.sockets.on('connection', function (socket) {
socket.on('txt', function(data) {
console.log(data);
socket.broadcast.emit("dataReceive", data)
})
});
server.listen(8080);