【发布时间】:2016-04-14 17:33:47
【问题描述】:
我最近开始使用 Socket.io,结果是 node.js,我有点卡住了。我什至不知道这是否是我的应用程序的实用解决方案,但希望有人可以提供帮助。
我这里只有一个带有复选框的网页,它向节点控制台报告它的状态,然后当 TCP 客户端连接时,它也会收到状态。
我想知道如何使这个事件连续,以便 TCP 客户端不断接收复选框状态的更新。
如果有人有任何想法,请告诉我,很抱歉代码太长...
服务器代码:
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(http);
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
socket.write(MYVAR);
}).listen(PORT, HOST);
客户端代码:
<!doctype html>
<html>
<head>
<title>Socket IO Test</title>
<form action="">
<input type='checkbox' onclick='checkbox1(this);'>Checkbox1</label>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
var number = 0;
function checkbox1(cb) {
socket.emit('checkbox1', 'checkbox 1 = ' + cb.checked);
return false;
}
</script>
</body>
</html>
干杯
【问题讨论】:
标签: javascript node.js sockets tcp socket.io