简体   繁体   English

Node.js Express不打印任何内容

[英]Node.js express does not print anything

So I moved app.listen to the top, but now it gives me an error that port is in use. 因此,我将app.listen移到顶部,但现在它给我一个错误,表明该端口正在使用中。 I believe this is because I set up my websocket on this port, but how do I do it then? 我相信这是因为我在此端口上设置了网络套接字,但是我该怎么办呢?

var server = require('websocket').server, http = require('http');
var express = require('express');
var app = express();
app.listen(8080);

var socket = new server({
    httpServer: http.createServer().listen(8080)
});


socket.on('request', function(request) {
    var connection = request.accept(null, request.origin);

    app.get('/', function(request, response) {
        var id = request.query.steamid;
        console.log("STEAMID:",id);
        response.send("I have received the ID: " + id);
    });

    connection.on('message', function(message) {
        connection.sendUTF(message);
    });

    connection.on('close', function(connection) {
        console.log('connection closed');
    });
}); 

I believe you need to listen on connection and not on request 我相信您需要在connection听,而不是在request

socket.on('connection', function(sock) {       
    sock.on('message', function(message) {
        sock.send(message);
    });

    sock.on('close', function() {
        console.log('connection closed');
    });
}); 

put your app.listen(3000); 把你的app.listen(3000); outside of request event. 请求事件之外。 so,your express server get chance to initialize port to listen. 这样,您的快递服务器就有机会初始化端口以进行监听。

Currently it is in callback of request event and it will get called once client-server connection of web-socket is established. 当前,它处于request event回调中,一旦建立了Web套接字的客户端-服务器连接,它将被调用。

As far as URL concern 就URL而言

ws://localhost:8080/?steamid=123456789

you have configured websocket to listen on port 8080.But your express is configured to listen port 3000.So it is not possible to catch request on express Server configured on different port which is requested through web-socket configured on another different port. 您已将websocket配置为侦听端口8080。但是将express配置为侦听端口3000。因此,无法在通过其他端口配置的web-socket请求的不同端口上配置的express服务器上捕获请求。

url should be like this. 网址应该是这样的。

http://localhost:3000/?steamid=123456789

because your express server using http protocol and not websocket 因为您的快递服务器使用http protocol and not websocket

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM