我有一個相鄰的兩臺筆記本電腦的設置,並希望發送它們之間的消息,我發現代碼時,客戶端和服務器都運行同一臺計算機,但它們在分開時不起作用。Python的套接字:如何連接兩臺計算機上相同的WiFi
#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,本地主機,192.168 ... < - IP從命令ifconfig。問題是什麼?我應該考慮什麼才能找到最佳解決方案?
它可以在一臺計算機上工作,但在服務器和客戶端位於不同計算機上時返回值爲 mySocket.connect((host,port))socket.gaierror:[Errno -2]名稱或服務未找到。 –
我想明白了,鑑於上述情況,您可以使用在ifconfig(在Linux上)中找到的ip作爲主機,我認爲它在Windows上是ipconfig。 –