te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Python Websockets can't connect over internet - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Python Websockets can't connect over internet - Stack Overflow

programmeradmin2浏览0评论

I'm just trying to get a very basic websocket connection over internet. The code seems fine - because it works when connecting to localhost - but for some reason fails when I try to use it over the internet. I'm using the websockets library, and my server looks like this:

#!/usr/bin/env python3

import asyncio
import websockets
from logging import getLogger, INFO, StreamHandler

logger = getLogger('websockets')
logger.setLevel(INFO)
logger.addHandler(StreamHandler())

clients = set()

async def handler(websocket, path):
    global clients
    clients.add(websocket)
    try:
        await asyncio.wait([ws.send("Hello!") for ws in clients])
        await asyncio.sleep(10)
    finally:
        clients.remove(websocket)

start_server = websockets.serve(handler, host='127.0.0.1', port=6969)

asyncio.get_event_loop().run_until_plete(start_server)
asyncio.get_event_loop().run_forever()

and the client looks like this:

<!DOCTYPE html>
<html lang="en"><head>
    <meta charset="UTF-8">
    <title>Chat</title>
</head>

<body style="margin:0">
    <script type="text/javascript">
        var ws = new WebSocket("ws://127.0.0.1:6969/");
        var messages = document.getElementById('messages');
        ws.onmessage = function (event) {
            var messages = document.getElementById('messages');
            var message = document.createElement('li');
            var content = document.createTextNode(event.data);
            message.appendChild(content);
            messages.appendChild(message);
        };
    </script>
    Messages:
    <ul id="messages"><li>Hello!</li></ul>


</body></html>

So the issue is that the client above works fine, until I run the server on my Ubuntu machine (and I've made sure to forward port 6969 to that machine) and try to connect over the internet. Hostname resolution is working fine, because I can ssh in to start the server, but trying to connect to the websocket always shows me the error message:

Firefox can’t establish a connection to the server at ws://<remote server url>:6969/.

or similiar for other browsers. Also, in case anyone was wondering, the logger isn't outputting anything useful (since the connection is failing the server isn't doing anything).

I'm just trying to get a very basic websocket connection over internet. The code seems fine - because it works when connecting to localhost - but for some reason fails when I try to use it over the internet. I'm using the websockets library, and my server looks like this:

#!/usr/bin/env python3

import asyncio
import websockets
from logging import getLogger, INFO, StreamHandler

logger = getLogger('websockets')
logger.setLevel(INFO)
logger.addHandler(StreamHandler())

clients = set()

async def handler(websocket, path):
    global clients
    clients.add(websocket)
    try:
        await asyncio.wait([ws.send("Hello!") for ws in clients])
        await asyncio.sleep(10)
    finally:
        clients.remove(websocket)

start_server = websockets.serve(handler, host='127.0.0.1', port=6969)

asyncio.get_event_loop().run_until_plete(start_server)
asyncio.get_event_loop().run_forever()

and the client looks like this:

<!DOCTYPE html>
<html lang="en"><head>
    <meta charset="UTF-8">
    <title>Chat</title>
</head>

<body style="margin:0">
    <script type="text/javascript">
        var ws = new WebSocket("ws://127.0.0.1:6969/");
        var messages = document.getElementById('messages');
        ws.onmessage = function (event) {
            var messages = document.getElementById('messages');
            var message = document.createElement('li');
            var content = document.createTextNode(event.data);
            message.appendChild(content);
            messages.appendChild(message);
        };
    </script>
    Messages:
    <ul id="messages"><li>Hello!</li></ul>


</body></html>

So the issue is that the client above works fine, until I run the server on my Ubuntu machine (and I've made sure to forward port 6969 to that machine) and try to connect over the internet. Hostname resolution is working fine, because I can ssh in to start the server, but trying to connect to the websocket always shows me the error message:

Firefox can’t establish a connection to the server at ws://<remote server url>:6969/.

or similiar for other browsers. Also, in case anyone was wondering, the logger isn't outputting anything useful (since the connection is failing the server isn't doing anything).

Share Improve this question edited Aug 29, 2017 at 16:46 ocket8888 asked Aug 29, 2017 at 16:34 ocket8888ocket8888 1,1401 gold badge15 silver badges35 bronze badges 4
  • on the server I don't change any code, the only difference is when it's running on the remote server I change the line var ws = new Websocket("ws://127.0.0.1:6969/"); to var ws = new Websocket("ws://<remote server url>:6969/"); on the client. – ocket8888 Commented Aug 29, 2017 at 16:43
  • the telnet mand properly resolves the IP address and attempts to connect but then says "connection refused". Also, if you could edit your ment to remove the url I'd appreciate it; I'm not ready for everyone to pentest me just yet :P (I'll edit it out of the question too - whoops) – ocket8888 Commented Aug 29, 2017 at 16:45
  • Change your websockets.serve() line to this: websockets.serve(handler, port=6969). That should work equally well in either environment. – Robᵩ Commented Aug 29, 2017 at 16:47
  • @Robᵩ I changed it to websockets.serve(handler, host="", port=6969) and now I can connect. If you wanna write an answer, I'd be happy to accept it, and I'd also appreciate an explanation of why what I did won't work. – ocket8888 Commented Aug 29, 2017 at 16:48
Add a ment  | 

1 Answer 1

Reset to default 14

Your line:

websockets.serve(handler, host='127.0.0.1', port=6969)

provides a specific address on which the websockets server listens. Your server will only listen on that address; any requests to any other address will never be seen.

From https://docs.python/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.create_server :

The host parameter can be a string, in that case the TCP server is bound to host and port. The host parameter can also be a sequence of strings and in that case the TCP server is bound to all hosts of the sequence. If host is an empty string or None, all interfaces are assumed and a list of multiple sockets will be returned (most likely one for IPv4 and another one for IPv6).

You have bound your webserver to 127.0.0.1, which is a special address that only ever refers to the local machine. This address is also known as localhost. No other machine can ever connect to your localhost.

The solution is to provide an empty string or None (the default value). In this case, your web server will listen for requests sent to any address.

websockets.serve(handler, port=6969)
发布评论

评论列表(0)

  1. 暂无评论