Python 客户没有';t从INTERNET上的不同计算机连接到服务器
我一直在开发一个非常简单的群组聊天程序。该程序在同一台计算机上测试时运行良好,但在互联网上的不同计算机之间不起作用 我已尝试禁用Windows防火墙 对不起,我不能缩小密码的范围。 该程序使用套接字和线程库 客户端代码:Python 客户没有';t从INTERNET上的不同计算机连接到服务器,python,Python,我一直在开发一个非常简单的群组聊天程序。该程序在同一台计算机上测试时运行良好,但在互联网上的不同计算机之间不起作用 我已尝试禁用Windows防火墙 对不起,我不能缩小密码的范围。 该程序使用套接字和线程库 客户端代码: import socket import threading SERVER_IP = "127.0.0.1" #This is changed to the servers PUBLIC IP when testing with another computer.
import socket
import threading
SERVER_IP = "127.0.0.1" #This is changed to the servers PUBLIC IP when testing with another computer.
SERVER_PORT = 9279
global name
global sock
def connect():
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_addres = (SERVER_IP, SERVER_PORT)
try:
sock.connect(server_addres)
print("Connected.")
return 1
except:
print("Cant connect to server.")
return 0
def send_msg():
global sock
while True:
try:
msg = name + " >> " + input()
sock.sendall(msg.encode())
except Exception as e:
print(e)
def recieve_msg():
global sock
server_active = 1
while True and server_active:
try:
recieved_msg = sock.recv(1024).decode()
print("\n" + recieved_msg)
except Exception as e:
print(e)
server_active = 0
def main():
global name
name = input("Enter name: ")
connected = connect()
while True and connected:
send_thread = threading.Thread(target=send_msg)
send_thread.start()
recv_thread = threading.Thread(target=recieve_msg)
recv_thread.start()
while recv_thread.is_alive():
recv_thread.join(timeout=0.1)
sock.close()
服务器代码:
import socket
import _thread
host = "My private IP"
port = 9279
global thread_active
thread_active = 1
global client_list
client_list = []
global addr
def on_new_client(clientsocket, pt):
global thread_active
global client_list
while True and thread_active:
global addr
try:
msg = clientsocket.recv(1024).decode()
print(msg + " " + str(addr))
for client in client_list:
client.send(msg.encode())
except Exception as e:
print("Client " + str(addr[0]) + ':' + str(addr[1]) + " disconnected (" + str(e) + ")")
if clientsocket in client_list:
client_list.remove(clientsocket)
print(client_list)
thread_active = 0
s = socket.socket()
print('Server started!')
print('Waiting for clients...')
s.bind((host, port)) # Bind to the port
s.listen(10) # Now wait for client connection.
while True:
c, addr = s.accept()
print('Got connection from', addr)
client_list.append(c)
_thread.start_new_thread(on_new_client, (c, 0))
thread_active = 1
s.close()
clientsocket.close()
已尝试将服务器文件中的代码更改为`host=“0.0.0.0”,并已尝试??如果计算机位于同一网络上,则需要使用本地IP地址。如果您试图通过网络(通过Internet)进行通信,则需要在相应的路由器上启用端口转发。“在不同的计算机之间,”:您不能使用
host=“127.0.0.1”
,这是localhost
==同一台计算机。您必须从服务器使用ip
,您可以从客户端使用ping
。请回答您的问题并说出哪个网络
局域网
或互联网
?@Ron:“在互联网上工作。”:1。使您的服务器
世界可访问。这需要@bkervian指出的路由器
配置。2.您的客户
必须使用互联网地址
,您的路由器
是从您的提供商那里分配的。相关@stovfl我只是想知道如果我不启用端口转发,著名的聊天应用程序是如何工作的?客户端是否也需要启用端口转发?