昨天直播时说到socket在模拟器上会有问题,模拟器会自己掉线,是我自写的不对吗。
node.js 上的代码
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require("path");
var filePath=path.join(__dirname,'index.html');
console.log(filePath);
app.get('/', function(req, res){
res.sendFile(filePath);
});
//绑定连接的监听
var i = 0
io.on('connection', function(socket){
console.log('a user connected');
//聊天数据的监听
socket.on('message', function(msg){
//全局广播消息
i++;
io.emit('m',msg,i);
console.log('message: ' + msg);
});
//绑定断线的监听
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
index.html 上的代码
<!doctype 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>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script>
var socket = io();
$('form').submit(function(){
console.log("Click send");
socket.emit('message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('m', function(msg,i){
console.log(msg,i)
$('#messages').append($('<li>').text(msg,i));
});
</script>
<li>hh</li>
</body>
</html>
在cocos creator 上的代码
onLoad: function () {
var socket = io.connect('http://Localhost:3000')
socket.on('m',(msg)=>{
cc.log(msg)
this.label.string =msg
})
},
在网页输入 东西后,一开始网页端和模拟器都会改变,但是表现的不同
网页端
模拟器
过一段时间模拟器会掉线.

此时输入,网页端会改变,模拟器不会变化。

