Python网络编程——编写一个简单的回显客户端/服务器应用

今天将python中socket模块的基本API学习完后,照着书上的实例编写一个套接字服务器和客户端。采用python3.5版本,在注释中会标明python2和python3的不同之处。

1.代码

(1)服务器端及对应代码解释

 # ! /usr/bin/env python
# -*- coding: utf-8 -*-
# 编写回显服务器 import socket
import sys
import argparse # 定义常量
host = 'localhost'
data_payload = 2048
backlog = 5 def echo_server(port): # 创建一个TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置TCP套接字关联选项——重用地址
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 建立套接字端口
server_address = (host, port)
print("Starting up echo server on %s port %s" % server_address) # 将socket绑定到server_address地址
sock.bind(server_address) # 监听客户端
# backlog指定最多允许多少个客户连接到服务器。它的值至少为1。收到连接请求后,这些请求需要排队,如果队列满,就拒绝请求。
# 这里设定为5
sock.listen(backlog)
# 在调用 Listen 之前,必须首先调用 Bind 方法,否则 Listen 将引发 SocketException。
while True:
print("Waiting to receive message from client") # 调用accept方法时,socket会时入“waiting”状态。客户请求连接时,方法建立连接并返回服务器。
# accept方法返回一个含有两个元素的 元组(connection,address)。第一个元素connection
# 是新的socket对象,服务器必须通过它与客户通信;第二个元素 address是客户的Internet地址。
client, address = sock.accept() # 指定data最大长度为2048字节
data = client.recv(data_payload)
if data:
print("Data: %s" % data)
client.send(data)
print("sent %s bytes back to %s" % (data, address))
# 关闭连接
client.close() if __name__ == '__main__':
# 创建一个解析对象,其中描述为"Socket Error Examples"
parser = argparse.ArgumentParser(description='Socket Server Example')
# 采用add_argument方法
# name or flags —— 必须的参数,该参数接收选项参数或者是位置参数
# action:
# (1)store —— 默认action模式,储存值到指定变量
# (2)store_const —— 储存值在参数的const部分指定,多用于实现非布尔的命令行flag
# (3)store_true/store_false —— 布尔开关。可以2个参数对应一个变量
# (4)append —— 储存值到列表,储存值在参数的const部分指定
# (5)append_const —— 储存值到列表,储存值在参数的const部分指定
# (6)version —— 输出版本信息然后退出
# type —— 把从命名行输入的结果转成设置的类型,通常用来检查值的范围,以及合法性。默认string  
# required —— 指定某个选项在命名中出现, 默认False, 若为 True, 表示必须输入该参数
# dest —— 把位置或者选项关联到一个特定的名字
parser.add_argument('--port', action="store", dest="port", type=int, required=True)
# 调用parse_args()方法进行解析
given_args = parser.parse_args()
port = given_args.port
echo_server(port) def bind(self, address): # real signature unknown; restored from __doc__
"""
bind(address) Bind the socket to a local address. For IP sockets, the address is a
pair (host, port); the host must refer to the local host. For raw packet
sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
"""
pass
def listen(self, backlog=None): # real signature unknown; restored from __doc__
"""
listen([backlog]) Enable a server to accept connections. If backlog is specified, it must be
at least 0 (if it is lower, it is set to 0); it specifies the number of
unaccepted connections that the system will allow before refusing new
connections. If not specified, a default reasonable value is chosen.
"""
pass

服务器端代码

(2)客户端及对应代码解释

 # ! /usr/bin/env python
# -*- coding: utf-8 -*-
# 编写回显客户端 import socket
import sys
import argparse host = 'localhost' def echo_client(port):
# 创建TCP socket连接
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取服务器端host和端口号
server_address = (host, port)
print("Connecting to %s port %s" % server_address)
sock.connect(server_address) try:
# 将message内容发送到服务器端
message = "Test message, This will be echoed"
print("Sending %s" % message)
# python2和python3此处不同
# python2—— sock.sendall(message)
# sendall()发送完整的TCP数据,成功返回None,失败抛出异常
sock.sendall(message.encode()) # 服务器端将发送的数据回传给客户端并打印
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = sock.recv(1024)
amount_received += len(data)
print("Received: %s" % data)
# 处理相对应错误
except socket.error as e:
print("socket error: %s" % str(e))
except Exception as e:
print("Other exception: %s" % str(e))
finally:
print("Closing connection to the server")
sock.close() if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Socket Server Example')
parser.add_argument('--port', action="store", dest="port", type=int, required=True)
given_args = parser.parse_args()
port = given_args.port
echo_client(port)

客户端代码

(3)运行结果

 1. 服务器端
Abel$ python3 1_13a_echo_server.py --port=9900
Starting up echo server on localhost port 9900
Waiting to receive message from client 2.客户端发送数据时,服务器端
Data: b'Test message, This will be echoed'
sent b'Test message, This will be echoed' bytes back to ('127.0.0.1', 62389)
Waiting to receive message from client 3.客户端
Abel$ python3 1_13b_echo_client.py --port=9900
Connecting to localhost port 9900
Sending Test message, This will be echoed
Received: b'Test message, This will be echoed'
Closing connection to the server
上一篇:2021-09-22


下一篇:CSS3学习之 animation 属性