【发布时间】:2017-07-09 17:46:09
【问题描述】:
我正在尝试学习套接字编程/网络,并启动并运行一个基本服务器。不幸的是,我只能从运行服务器的机器连接到它。我使用telnet localhost 9999 从命令提示符连接。这在同一网络上的不同机器上不起作用(如在没有运行服务器的不同电脑上)。我试过telnet "my local ip" 9999 无济于事,在任何地方都找不到解决方案。任何帮助表示赞赏。我正在运行 python 3.6.1
这是我的代码
import socket
import sys
from _thread import *
import webbrowser
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 9999
try:
s.bind((host,port))
except socket.error as e:
print (str(e))
s.listen(5)
def threaded_client(conn):
conn.send(str.encode("welcome, would you like to listen to a song? \n"))
while True:
reply = ""
data = conn.recv(2048)
if data == b's':
conn.send(str.encode("\n hi\n"))
webbrowser.open('https://www.youtube.com/watch?v=DLzxrzFCyOs')
if not data:
break
conn.sendall(str.encode(reply))
print (data)
conn.close()
while True:
conn, addr = s.accept()
print("connected to:" +addr[0]+":"+str(addr[1]))
start_new_thread(threaded_client,(conn,))
当我尝试连接时,这是我收到的消息 C:\Users\Douglas Rouse>telnet 127.0.0.1 9999
Connecting To 127.0.0.1...Could not open connection to the host, on port 9999: Connect failed
【问题讨论】:
-
正确缩进 thread_client 函数时适用于 python3.5。
-
有趣,可能意味着它不是代码相关的问题。
-
注意我是在 Ubuntu 17.04 上运行的,你好像是在 windows 下运行的?
-
是的,我在 windows 上运行,抱歉没想到要提这个
-
RFC 3330, Special-Use IPv4 Addresses:127.0.0.0/8 - 此块被分配用作 Internet 主机环回地址。由更高级别协议发送到该块内任何地址的数据报应在主机内部循环。这通常仅使用 127.0.0.1/32 来实现环回,但此块内的任何地址都不应该出现在任何地方的任何网络上 [RFC1700,第 5 页]。
标签: python-3.x sockets networking