开发人员可以使用大量的第三方 python 工具创建网络客户端和服务器, 这些第三方工具的核心模块是 socket 模块
这个模块展示了快速创建 TCP 服务端及客户端, 使用原始套接字等所必须的代码.
import socket
import threading
def tcp_client(target_host=None,target_port=None,send_data=None):
""" TCP 客户端 """
target_host = target_host if target_host else "www.baidu.com"
target_port = target_port if target_port else 80
send_data = send_data if send_data else b"GET / HTTP/1.1\r\nHost: baidu.com\r\n\r\n"
# 建立一个 socket 对象
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接客户端
client.connect((target_host, target_port))
# 发送数据
client.send(send_data)
# 接收数据
response = b''
while 1:
res = client.recv(1024)
response += res
if len(res)<1024:
break
print(response)
def tcp_server(bind_ip=None,bind_port=None,response_data=None):
""" TCP 服务器 """
bind_ip = bind_ip if bind_ip else "192.168.1.80"
bind_port = bind_port if bind_port else 8000
response_data = response_data if response_data else b"Yes!"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[*] Listening on %s:%d"%(bind_ip, bind_port))
# 客户端处理线程
def handle_client(client_socket):
# 打印客户端发送的内容
request = client_socket.recv(1024)
print("[*] Received: %s"%request)
# 返还一个数据包
client_socket.send(response_data)
client_socket.close()
while 1:
client, addr = server.accept()
print("[*] Accepted connection from: %s:%d"%(addr[0],addr[1]))
# 挂起客户端线程, 处理传入的数据
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()
if __name__ == '__main__':
host = "192.168.1.80"
port = 8000
# 开启服务端
server = threading.Thread(target=tcp_server,args=(host,port,b"Server: Hello client"))
server.start()
# 开启客户端
client = threading.Thread(target=tcp_client,args=(host,port,b'Client: My name is client'))
client.start()