时间:2021-07-01 10:21:17 帮助过:14人阅读
1、基于多线程实现并发的套接字通信
客户端
+ View Code?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# _*_ coding: utf-8 _*_
from socket import *
ip_port = ( ‘127.0.0.1‘ , 9999 )
client = socket(AF_INET,SOCK_STREAM)
client.connect(ip_port)
while True :
cmd = input ( ">>>" ).strip()
if not cmd:
continue
client.send(cmd.encode( ‘utf-8‘ ))
data = client.recv( 1024 )
print (data.decode( ‘utf-8‘ ))
client.close()
|
服务端
+ View Code?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import multiprocessing
import threading
import socket
ip_port = ( ‘127.0.0.1‘ , 9999 )
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(ip_port)
s.listen( 5 )
def action(conn):
while True :
data = conn.recv( 1024 )
print (data)
conn.send(data.upper())
if __name__ = = ‘__main__‘ :
while True :
conn,addr = s.accept()
p = threading.Thread(target = action,args = (conn,))
p.start()
|
2、编写一个简单的文本处理工具,具备三个任务,一个接收用户输入,一个将用户输入的内容格式化成大写,一个将格式化后的结果存入文件
+ View Code?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# _*_ coding: utf-8 _*_
# 练习二:三个任务,一个接收用户输入,一个将用户输入的内容格式
# 化成大写,一个将格式化后的结果存入文件
from threading import Thread
msg_l = []
format_l = []
def talk():
while True :
msg = input ( ">>>" ).strip()
if not msg:
break
msg_l.append(msg)
def format_msg():
while True :
if msg_l:
res = msg_l.pop()
format_l.append(res.upper())
def save():
while True :
if format_l:
with open ( ‘db.txt‘ , ‘a‘ ,encoding = ‘utf-8‘ ) as f:
res = format_l.pop()
f.write( ‘%s\n‘ % res)
if __name__ = = ‘__main__‘ :
t1 = Thread(target = talk)
t2 = Thread(target = format_msg)
t3 = Thread(target = save)
t1.start()
t2.start()
t3.start()
|
第四模块:网络编程进阶&数据库开发 练习
标签:练习 write 习题 func from send ring open plain