27 网络通信协议 tcp udp subprocess

1.模块subprocess

import subprocess

cmd_str = input('请输入指令>>>')

sub_obj = subprocess.Popen(
cmd_str,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
) print(sub_obj.stdout.read().decode('gbk'))
print('错误信息>>>>',sub_obj.stderr.read().decode('gbk'))

2.时间服务器

#服务端
from socket import *
from time import strftime ip_port = ('127.0.0.1', 9000)
bufsize = 1024 tcp_server = socket(AF_INET, SOCK_DGRAM)
tcp_server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
tcp_server.bind(ip_port) while True:
msg, addr = tcp_server.recvfrom(bufsize)
print('===>', msg) if not msg:
time_fmt = '%Y-%m-%d %X'
else:
time_fmt = msg.decode('utf-8')
back_msg = strftime(time_fmt) tcp_server.sendto(back_msg.encode('utf-8'), addr) tcp_server.close() #客户端
from socket import *
ip_port=('127.0.0.1',9000)
bufsize=1024 tcp_client=socket(AF_INET,SOCK_DGRAM) while True:
msg=input('请输入时间格式(例%Y %m %d)>>: ').strip()
tcp_client.sendto(msg.encode('utf-8'),ip_port) data=tcp_client.recv(bufsize)
 

3.qq聊天

#服务端
#_*_coding:utf-8_*_
import socket
ip_port=('127.0.0.1',8081)
udp_server_sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udp_server_sock.bind(ip_port) while True:
qq_msg,addr=udp_server_sock.recvfrom(1024)
print('来自[%s:%s]的一条消息:\033[1;44m%s\033[0m' %(addr[0],addr[1],qq_msg.decode('utf-8')))
back_msg=input('回复消息: ').strip() udp_server_sock.sendto(back_msg.encode('utf-8'),addr) #客户端
#_*_coding:utf-8_*_
import socket
BUFSIZE=1024
udp_client_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) qq_name_dic={
'金老板':('127.0.0.1',8081),
'哪吒':('127.0.0.1',8081),
'egg':('127.0.0.1',8081),
'yuan':('127.0.0.1',8081),
} while True:
qq_name=input('请选择聊天对象: ').strip()
while True:
msg=input('请输入消息,回车发送,输入q结束和他的聊天: ').strip()
if msg == 'q':break
if not msg or not qq_name or qq_name not in qq_name_dic:continue
udp_client_socket.sendto(msg.encode('utf-8'),qq_name_dic[qq_name]) back_msg,addr=udp_client_socket.recvfrom(BUFSIZE)
print('来自[%s:%s]的一条消息:\033[1;44m%s\033[0m' %(addr[0],addr[1],back_msg.decode('utf-8'))) udp_client_socket.close()

socket参数的详解

socket.socket(family=AF_INET,type=SOCK_STREAM,proto=0,fileno=None)
创建socket对象的参数说明:
27 网络通信协议 tcp udp subprocess
·
上一篇:Netty源码分析-- 处理客户端接入请求(八)


下一篇:源码分析 Kafka 消息发送流程(文末附流程图)