建立出站连接

我最近一直在修改python套接字模块,我遇到了一个问题。这是我的python服务器端脚本(im使用python3.8.2)


import socket


#defin socket object

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((socket.gethostname(), 0))

s.listen(5)

while True:

    clientsocket, address = s.accept()

    print(f"connection from client has been established")

    clientsocket.send(bytes("welcome to the server!", "utf-8"))


我的服务器端脚本运行正常,但是当我运行客户端脚本时


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((socket.gethostname(127.0.0.1), 0))

msg = s.recv(1024)

print(msg.decode("utf-8")) 

我得到以下内容:


File "client.py", line 3

    s.connect((socket.gethostname(127.0.0.1), 0))

                                       ^

SyntaxError: invalid syntax

我尝试将IP更改为我的计算机主机名,并给出以下内容:


raceback (most recent call last):

  File "client.py", line 3, in <module>

    s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))

NameError: name 'LAPTOP' is not defined


当年话下
浏览 126回答 2
2回答

肥皂起泡泡

存在多个问题:指定 IP 地址和主机名时,必须将其格式化为字符串(例如 和 )。指定它们而不带引号会导致Python尝试将它们解释为其他标记,例如变量名称,保留关键字,数字等,这会导致诸如语法错误和NameError之类的错误。"127.0.0.1""LAPTOP-XXXXXXX"socket.gethostname()&nbsp;不采用参数在调用中指定端口 0 会导致分配一个随机的高编号端口,因此您需要对使用的端口进行硬编码,或者在客户端中动态指定正确的端口(例如,在执行程序时将其指定为参数)socket.bind()在服务器代码中,可能最终不会使用环回地址。此处的一个选项是使用空字符串,这会导致接受任何 IPv4 地址上的连接。socket.gethostname()下面是一个有效的实现:server.pyimport socketHOST = ''PORT = 45555s = 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:&nbsp; &nbsp; client_socket, client_addr = s.accept()&nbsp; &nbsp; print("connection from {}:{} established".format(client_addr[0], client_addr[1]))&nbsp; &nbsp; client_socket.send(bytes("welcome to the server!", "utf-8"))client.pyimport socketHOST = '127.0.0.1'PORT = 45555s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((HOST, PORT))msg = s.recv(1024)print(msg.decode("utf-8"))来自服务器的输出:$ python3 server.pylistening on 0.0.0.0:45555connection from 127.0.0.1:51188 establishedconnection from 127.0.0.1:51244 established客户端输出:$ python3 client.pywelcome to the server!$ python3 client.pywelcome to the server!

达令说

在文件内容中,您将有一个IP地址映射,“127.0.1.1”到您的主机名。这将导致名称解析获得 127.0.1.1。只需注释此行。因此,LAN中的每个人都可以在与您的IP(192.168.1.*)连接时接收数据。用于管理多个客户端。/etc/hoststhreading以下是服务器和客户端代码:服务器代码:import socketimport osfrom threading import Threadimport threadingimport timeimport datetimedef listener(client, address):&nbsp; &nbsp; print ("Accepted connection from: ", address)&nbsp; &nbsp; with clients_lock:&nbsp; &nbsp; &nbsp; &nbsp; clients.add(client)&nbsp; &nbsp; try:&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; while True:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; client.send(a)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time.sleep(2)&nbsp; &nbsp;&nbsp; &nbsp; finally:&nbsp; &nbsp; &nbsp; &nbsp; with clients_lock:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clients.remove(client)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; client.close()clients = set()clients_lock = threading.Lock()host = socket.getfqdn()&nbsp; # it gets ip of lanport = 10016s = 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:&nbsp; &nbsp; client, address = s.accept()&nbsp; &nbsp; timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")&nbsp; &nbsp; a = ("Hi Steven!!!" + timestamp).encode()&nbsp; &nbsp; th.append(Thread(target=listener, args = (client,address)).start())s.close()客户端代码:import socketimport osimport times = socket.socket()&nbsp;&nbsp;host = '192.168.1.43' #my server ip&nbsp;port = 10016print(host)print(port)s.connect((host, port))while True:&nbsp; &nbsp; print((s.recv(1024)).decode())s.close()&nbsp;输出:(base) paulsteven@smackcoders:~$ python server.py&nbsp;Server is listening for connections...Accepted connection from:&nbsp; ('192.168.1.43', 38716)(base) paulsteven@smackcoders:~$ python client.py&nbsp;192.168.1.4310016Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AMHi Steven!!!Feb 19 2020,Wed, 11:13:17 AMHi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python