我想运行一个javascript程序,而不是在node.js中终止:---
这是using while(1);
吗?
在这个javascript程序里面,我创建了一个websocket&列出来。
每当数据出现在websocket上时,它就会抛出console.log。
test.js: -
var tt = new websocket_fun();
function websocket_fun()
{
var temp = new websocket_create();
while(1);
}
function websocket_create()
{
// Open the socket
this.socket = new WebSocket( "192.168.0.11:8080");
// Bind events
this.socket.onmessage = this.onMessagesocket.bind(this);
this.socket.onopen = this.onOpensocket.bind(this);
this.socket.onclose = this.onClosesocket.bind(this);
}
websocket_create.prototype.onMessagesocket = function(msg)
{
console.log(msg);
}
websocket_create.prototype.onOpensocket = function(msg)
{
console.log('Open websocket');
}
websocket_create.prototype.onClosesocket = function(msg)
{
console.log('Close websocket');
}
跑:--- node test.js
答案 0 :(得分:0)
while(1)
不是一个好主意,因为它会阻止你的程序并占用大量的处理器能力。
可能有其他方法可以做到这一点,但我能想到的最简单的方法是使用setInterval
如果您无法执行任何操作,则可以使用空函数。
setInterval(function(){}, 10000);
答案 1 :(得分:0)
它比这复杂一点,你需要一个http服务器来监听请求,只需使用这段代码来理解它:
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});