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
添加回答
举报