python - 简单socket服务器的基本理解

标签 python sockets networking tcp

我是套接字编程的新手,正在尝试了解套接字的工作原理。目前我正在尝试使用 python 套接字库来查看它是如何工作的。

现在有几件事我无法全神贯注。 让我们举个例子,如图here使用 Python 套接字库用 Python 编写的简单回显客户端和服务器的示例。

echo 服务器 如下所示 # echo_server.py 导入套接字

host = ''        # Symbolic name meaning all available interfaces
port = 12345     # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

echo 客户端如下所示

# echo_client.py
import socket

host = socket.gethostname()    
port = 12345                   # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))

我的问题

  1. 在 echo_server.py 中,当我说 conn, addr = s.accept() 时,accept() 做两件事。 1. 它返回连接客户端的地址(ip 和端口),存储在 addr 和 2. 它创建一个新的套接字(称为客户端套接字),可以在此处使用 conn 引用,并用于与连接的客户端进行交互。

    Now what happens when another client also connects to this server? Does the conn and addr variables get overwritten with the new values? Or how is it handled?

  2. 再次在 echo_server.py 中,s.listen(1) 建议最多允许 1 个积压,我似乎只在理论上理解它是服务器希望允许继续等待的最大客户端数在队列中,而服务器正忙于处理已经连接的客户端。

    Is there some simple practical example to demo this ?

最佳答案

Now what happens when another client also connects to this server? Does the conn and addr variables get overwritten with the new values? Or how is it handled?

正如 Rob 在另一个答案中指出的那样,您的代码将只接受一个客户端。必须为来自客户端的任何连接请求调用 accept。并相应地编码。现在回答您的问题,是的, (conn,addr) 对将被覆盖。在为新连接再次调用 accept 之前,代码应该注意将它们传递给某个连接线程。

Is there some simple practical example to demo this ?s there some simple practical example to demo this ?

在接受多个客户端的更新代码中,尝试在几次连接后不要调用 accept 并注意 TCP 连接状态表(例如 netstat)以查看行为不同的积压值。

关于python - 简单socket服务器的基本理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39541706/

相关文章:

c - 如何从 addrinfo 获取 sin6_addr?

c++ - 套接字接收调用卡住线程大约。 5秒

javascript - Websocket - 在触发 onclose 之前发送一些内容

python - 为什么 numpy 向量化比 for 循环慢

python - python中的 "for key in dict"是否总是以固定顺序迭代?

python - TensorFlow embedding_rnn_decoder 'Tensor' 对象不可迭代

python - 访问 Scapy 的内部协议(protocol)层

python - 如何在 Python 中设置直方图的 y 轴?

c - struct ip 和 struct iphdr 的区别

java - 将 webapp 从本地主机移动到服务器 - 找不到页面