在Godaddy主机上运行的Node.js WebSocket服务器运行,但客户端无法与服务器连接

时间:2019-01-22 10:20:16

标签: node.js websocket

我已经厌倦了在Godaddy托管中运行Node.js WebSocket,因此客户端无法与Web托管上的服务器连接,但是在localhost上它可以工作!我还编辑了.htacces,但是没有用!

当我尝试用Python编写服务器代码时,它对我来说很好用,但是Node.js不起作用。我应该使用Node.js,因为它很好地支持了我的项目。

我将在下面添加服务器代码和客户端代码:

服务器

const express = require('express');
const  http = require('http');
const WebSocket = require('ws');

const app = express();

//initialize a simple http server
const server = http.createServer(app);

//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) => {

    //connection is up, let's add a simple simple event
    ws.on('message', (message) => {

        //log the received message and send it back to the client
        console.log('received: %s', message);
        ws.send('Hello, you sent -> ${message}');
    });

    //send immediatly a feedback to the incoming connection
    ws.send('Hi there, I am a WebSocket server');
});

//start our server
server.listen(process.env.PORT || 8999, () => {
    console.log('Server started on port ${server.address().port} :)');
});

客户

import WebSocket

try:
    import thread
except for ImportError:
    import _thread as the thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        while True :
            input_func = None
            try:
                input_func = raw_input
            except NameError:
                input_func = input

            username = input_func("Username:")
            ws.send(username)
            time.sleep(1)
             ws.close()
             print("thread terminating...")
thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:8181/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

0 个答案:

没有答案