2 回答

TA貢獻1829條經驗 獲得超6個贊
存在多個問題:
指定 IP 地址和主機名時,必須將其格式化為字符串(例如 和 )。指定它們而不帶引號會導致Python嘗試將它們解釋為其他標記,例如變量名稱,保留關鍵字,數字等,這會導致諸如語法錯誤和NameError之類的錯誤。
"127.0.0.1"
"LAPTOP-XXXXXXX"
socket.gethostname()
不采用參數在調用中指定端口 0 會導致分配一個隨機的高編號端口,因此您需要對使用的端口進行硬編碼,或者在客戶端中動態指定正確的端口(例如,在執行程序時將其指定為參數)
socket.bind()
在服務器代碼中,可能最終不會使用環回地址。此處的一個選項是使用空字符串,這會導致接受任何 IPv4 地址上的連接。
socket.gethostname()
下面是一個有效的實現:
server.py
import socket
HOST = ''
PORT = 45555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
host_addr = s.getsockname()
print("listening on {}:{}".format(host_addr[0], host_addr[1]))
s.listen(5)
while True:
client_socket, client_addr = s.accept()
print("connection from {}:{} established".format(client_addr[0], client_addr[1]))
client_socket.send(bytes("welcome to the server!", "utf-8"))
client.py
import socket
HOST = '127.0.0.1'
PORT = 45555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
msg = s.recv(1024)
print(msg.decode("utf-8"))
來自服務器的輸出:
$ python3 server.py
listening on 0.0.0.0:45555
connection from 127.0.0.1:51188 established
connection from 127.0.0.1:51244 established
客戶端輸出:
$ python3 client.py
welcome to the server!
$ python3 client.py
welcome to the server!

TA貢獻1821條經驗 獲得超6個贊
在文件內容中,您將有一個IP地址映射,“127.0.1.1”到您的主機名。這將導致名稱解析獲得 127.0.1.1。只需注釋此行。因此,LAN中的每個人都可以在與您的IP(192.168.1.*)連接時接收數據。用于管理多個客戶端。/etc/hoststhreading
以下是服務器和客戶端代碼:服務器代碼:
import socket
import os
from threading import Thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.getfqdn() # it gets ip of lan
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = ("Hi Steven!!!" + timestamp).encode()
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
客戶端代碼:
import socket
import os
import time
s = socket.socket()
host = '192.168.1.43' #my server ip
port = 10016
print(host)
print(port)
s.connect((host, port))
while True:
print((s.recv(1024)).decode())
s.close()
輸出:
(base) paulsteven@smackcoders:~$ python server.py
Server is listening for connections...
Accepted connection from: ('192.168.1.43', 38716)
(base) paulsteven@smackcoders:~$ python client.py
192.168.1.43
10016
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
添加回答
舉報