gpt4 book ai didi

Python 套接字 : how to connect between two computers on the same wifi

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:28 25 4
gpt4 key购买 nike

我设置了两台并排的笔记本电脑,想在它们之间发送消息,我发现当客户端和服务器都在同一台计算机上时代码可以工作,但当它们在同一台计算机上时它不会工作分离。

#SERVER
import socket

def Main():
host = "localhost"
port = 5000

mySocket = socket.socket()
mySocket.bind((host,port))

mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
while True:
data = conn.recv(1024).decode()
if not data:
break
print ("from connected user: " + str(data))

data = str(data).upper()
print ("sending: " + str(data))
conn.send(data.encode())

conn.close()

if __name__ == '__main__':
Main()


#CLIENT
import socket

def Main():
host = '0.0.0.0'#127.0.0.1
port = 5000

mySocket = socket.socket()
mySocket.connect((host,port))

message = input(" -> ")

while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()

print ('Received from server: ' + data)

message = input(" -> ")

mySocket.close()

if __name__ == '__main__':
Main()

我尝试了很多不同的地址,包括 0.0.0.0、localhost、192.168... <- ifconfig 的 ip。问题是什么?我应该研究什么以获得最佳解决方案?

最佳答案

您需要告诉客户端您的服务器在您的网络上的地址和端口。您还需要告诉服务器要监听的地址和端口。

为方便起见,让我们绑定(bind)服务器的所有 IP 地址。为此,将服务器代码中的主机设置为“0.0.0.0”

对于客户端配置,您必须输入服务器地址。为此,我会在服务器代码中放置一行以显示该机器的主机名。

#SERVER
import socket

def Main():
host = "0.0.0.0"
port = 5000

print socket.gethostname()

mySocket = socket.socket()
mySocket.bind((host,port))

mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
while True:
data = conn.recv(1024).decode()
if not data:
break
print ("from connected user: " + str(data))

data = str(data).upper()
print ("sending: " + str(data))
conn.send(data.encode())

conn.close()

if __name__ == '__main__':
Main()


#CLIENT
import socket

def Main():
host = #put hostname here
port = 5000

mySocket = socket.socket()
mySocket.connect((host,port))

message = input(" -> ")

while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()

print ('Received from server: ' + data)

message = input(" -> ")

mySocket.close()

if __name__ == '__main__':
Main()



关于Python 套接字 : how to connect between two computers on the same wifi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41294848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com