python 学习_第四模块 并发编程(多线程)
2020-12-13 02:34
标签:ica size __name__ cli art ide name strip one python 学习_第四模块 并发编程(多线程) 1 开启线程方式 基于套接字实现多线程 python 学习_第四模块 并发编程(多线程) 标签:ica size __name__ cli art ide name strip one 原文地址:https://www.cnblogs.com/augustyang/p/11044332.html
from threading import Thread
import time
def say(name):
time.sleep(2)
print("%s hello"%name)
if __name__ =="__main__":
t = Thread(target=say,args=("alex",))
t.start()
print("主线程")
from threading import Thread
import time
class say(Thread):
def __init__ (self,name):
super().__init__()
self.name = name
def run(self):
time.sleep(2)
print("%s say hello" %self.name)
if __name__ == "__main__":
t = say("alex")
t.start()
print("主线程")
from socket import *
from threading import Thread
def communicate(conn):
while True:
try:
data = conn.recv(1024)
if not data:break
conn.send(data.upper())
except ConnectionResetError:
break
conn.close()
def server(ip,port):
server = socket(AF_INET,SOCK_STREAM)
server.bind((ip,port))
server.listen(5)
while True:
conn,addr = server.accept()
t = Thread(target=communicate,args=(conn,))
t.start()
server.close()
if __name__ == "__main__":
server("127.0.0.1",8080)
from socket import *
client = socket(AF_INET,SOCK_STREAM)
client.connect(("127.0.0.1",8080))
while True:
msg = input(">>: ").strip()
if not msg:continue
client.send(msg.encode("utf-8"))
data = client.recv(1024)
print(data.decode("utf-8"))
client.close()