在套接字库中使用 AF_INET 时出现类型错误

TypeError when using AF_INET in the sockets library

我正在使用 Python 的套接字库。我正在尝试制作本地服务器。服务器运行正常,但客户端运行不正常。当我说我想连接到 AF_INET 时,它给了我一个 TypeError。它说 AF_INET 地址必须是一个元组,当它是一个字符串时。

这是我的代码:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(socket.gethostname())
print("client successfully started")
msg = s.recv(1024)
print(msg.decode("utf-8"))

我正在使用 3.10.0 版(python),如果有帮助的话。

connect函数接受一个tuple,所以你需要一组额外的括号。不清楚您要用 gethostname 做什么。此外,您需要有一个端口号才能连接。如果您正在尝试收听 localhost,代码将如下所示:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Add socket.gethostbyname and add port number
s.connect((socket.gethostbyname(socket.gethostname()), 8089)) # Add another set of parentheses as you need a tuple
print("client successfully started")
msg = s.recv(1024)
print(msg.decode("utf-8"))

即使这样也可能导致 ConnectionRefusedError: [Errno 61] Connection refused 错误,因为您可能不得不使用服务器的 IP 地址。类似于:192.168.0.1。要获取您的 IP 地址,请在命令提示符下执行 ipconfig(在 Windows 上)。

所以正确的代码应该是这样的:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect('192.168.0.1', 8089)) # Your IP instead of 192.168.0.1
print("client successfully started")
msg = s.recv(1024)
print(msg.decode("utf-8"))

来自 socket 文档:

  • A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in internet domain notation like 'daring.cwi.nl' or an IPv4 address like
    '100.50.200.5', and port is an integer.

    • For IPv4 addresses, two special forms are accepted instead of a host address: '' represents INADDR_ANY, which is used to bind to all interfaces, and the string '<broadcast>' represents
      INADDR_BROADCAST. This behavior is not compatible with IPv6, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.

对于本地服务器,客户端可以只使用'localhost'

示例:

from socket import *

PORT = 5000

# for server
s = socket()  # AF_INET and SOCK_STREAM are the default
s.bind(('',PORT))  # must be a 2-tuple (note the parentheses)
s.listen()
c,a = s.accept()

# for client
s = socket()
s.connect(('localhost',PORT))

我找到答案了!

这里是所有和我有同样问题的人的代码

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),3000)) #you can use another port if you want
s.listen(5)
print("server successfully started")
while True:
    clientsocket, address = s.accept()
    print(f"connection has been established from {address}")
    clientsocket.send(bytes("Welcome to the chatroom!", "utf-8")) #this sends message to the client in utf-8