套接字服务器的代码和套接字客户端的代码可以在我的本地主机上完美运行,但是当我在Ubuntu服务器上运行套接字服务器的代码时,本地主机上的套接字客户端的代码无法连接到Ubuntu服务器。并且Ubuntu Server上的socket-client代码无法连接到我的localhost服务器。
socket-server.py
import socket
import threading
def bbs(conn):
user_list.append(conn)
try:
while 1:
msg = conn.recv(1024)
if msg:
for user in user_list:
user.send(msg)
except ConnectionResetError:
user_list.remove(conn)
conn.close()
user_list = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 18000))
server.listen()
while 1:
conn, addr = server.accept()
t = threading.Thread(target=bbs, args=(conn,))
t.start()
socket-client.py
import socket
import threading
import time
def send_msg():
while 1:
msg = input()
client.send((name + ':' + msg).encode('utf-8'))
def recv_msg():
while 1:
msg = client.recv(1024)
if msg:
try:
print(msg.decode('utf-8'))
time.sleep(1)
except UnicodeDecodeError:
pass
name = input('请输入你的昵称:')
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('10.26.8.132', 18000))
sendmsg_thread = threading.Thread(target=send_msg)
recvmsg_thread = threading.Thread(target=recv_msg)
sendmsg_thread.start()
recvmsg_thread.start()
服务器始终在等待连接,客户端报告错误:
TimeoutError: [WinError 10060] The connection attempt failed because the connecting party did not respond correctly after a period of time or because the connecting host did not respond.
答案 0 :(得分:0)
如果该方法在您的本地主机上没有问题,但不是通过网络连接运行,则可以,这可能是客户端和服务器上的防火墙问题。您可以使用“ nc”(netcat)来测试从客户端到服务器的连接。