为了账号安全,请及时绑定邮箱和手机立即绑定

建立出站连接

建立出站连接

当年话下 2022-08-02 17:18:35
我最近一直在修改python套接字模块,我遇到了一个问题。这是我的python服务器端脚本(im使用python3.8.2)import socket#defin socket objects = 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 sockets = 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
查看完整描述

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!


查看完整回答
反对 回复 2022-08-02
?
达令说

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


查看完整回答
反对 回复 2022-08-02
  • 2 回答
  • 0 关注
  • 125 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信