python TCP编程

1.socket

服务端和客户端通过socket套接字进行通信

2.服务端

import socket
import threading def tcp_handler(connect_sock, addr):
print('accept connection from %s:%s' % addr)
# 向客户端发送消息
connect_sock.send(b'welcome!')
while True:
# 阻塞,接收客户端消息
data = connect_sock.recv(1024)
if not data or data.decode('utf-8') == 'exit':
break
# 向客户端发送消息响应
connect_sock.send(b'hello %s' % data)
# 关闭连接socket
connect_sock.close()
print('connection from %s:%s closed' % addr) # 创建socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定地址,端口
server_socket.bind(('127.0.0.1', 9999)) # 监听连接, 参数为等待连接的最大数目
server_socket.listen(5) print('waiting for connection') # 循环接收来自客户单的连接请求
while True:
# 接收客户端连接,返回新的连接socket,客户端地址
connect_sock, addr = server_socket.accept()
# 创建新线程,处理TCP连接
t = threading.Thread(target=tcp_handler, args=(connect_sock, addr))
t.start()

3.客户端

import socket

# 创建socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立连接
client_socket.connect(('127.0.0.1', 9999)) # 阻塞,接收欢迎消息
print(client_socket.recv(1024)) for data in [b'shijingjing', b'renjiangfeng', b'huiyunyun']:
# 发送数据
client_socket.send(data)
print(client_socket.recv(2014)) client_socket.send(b'exit') client_socket.close()

4.运行结果

运行服务端tcp_server.py:

python TCP编程

运行客户端tcp_client.py:

python TCP编程

上一篇:[nginx] - 使用nginx实现反向代理,动静分离,负载均衡,session共享


下一篇:vue中监听返回键