[英]How to connect with Python Sockets to another computer on the same network
So I was trying to figure out a way to use sockets to make a terminal-based chat application, and I managed to do it quite well.所以我试图找出一种方法来使用 sockets 来制作基于终端的聊天应用程序,并且我设法做得很好。 Because I could only test it on one computer, I didn't realize that it might not work on different computers.因为我只能在一台计算机上测试它,所以我没有意识到它可能无法在不同的计算机上运行。 My code is as simple as this:我的代码很简单:
# Server
import socket
HOST = "0.0.0.0"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print("Connected to", addr)
data = conn.recv(1024)
print("Received:", data.decode())
conn.sendall(data)
# Client
import socket
HOST = "192.168.0.14"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello this is a connection")
data = s.recv(1024)
print("Received:", data.decode())
I've tried changing the ip to 0.0.0.0, use gethostname a lot of other things, but it just doesn't work.我尝试将 ip 更改为 0.0.0.0,使用 gethostname 很多其他东西,但它不起作用。 The server is up and running, but the client can't connect.服务器已启动并正在运行,但客户端无法连接。 Can someone help me?有人能帮我吗?
I believe that 0.0.0.0 means connect from anywhere which means that you have to allow port 5555 through your firewall.我相信 0.0.0.0 意味着从任何地方连接,这意味着您必须允许端口 5555 通过防火墙。
Instead of 0.0.0.0 use localhost as the address in both the client and the server.而不是 0.0.0.0 使用 localhost 作为客户端和服务器中的地址。
I just tested your code using localhost
for the server and the client and your program worked.我刚刚使用localhost
为服务器和客户端测试了您的代码,并且您的程序正常工作。
server:服务器:
Connected to ('127.0.0.1', 53850)
Received: Hello this is a connection
client:客户:
Received: Hello this is a connection
As you can see, all that I changed was the address on both the server and the client.如您所见,我更改的只是服务器和客户端上的地址。 If this doesn't work then there is something outside of your program that is preventing you from success.如果这不起作用,那么您的程序之外的某些东西会阻止您成功。 It could be a permissions issue or another program is listening on port 5555.这可能是权限问题或另一个程序正在侦听端口 5555。
server.py服务器.py
# Server
import socket
HOST = "0.0.0.0"
HOST = "localhost"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print("Connected to", addr)
data = conn.recv(1024)
print("Received:", data.decode())
conn.sendall(data)
if __name__ == '__main__':
pass
client.py客户端.py
# Client
import socket
HOST = "localhost"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello this is a connection")
data = s.recv(1024)
print("Received:", data.decode())
if __name__ == '__main__':
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.