码迷,mamicode.com
首页 > 其他好文 > 详细

socketserver,threading

时间:2018-09-06 23:00:38      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:strong   wro   elf   朋友   while   threading   强制   font   strip()   

一,socketserver 

#server
import socketserver
class Myserver(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "127.0.0.1", 9999

    # 设置allow_reuse_address允许服务器重用地址
    socketserver.TCPServer.allow_reuse_address = True
    # 创建一个server, 将服务地址绑定到127.0.0.1:9999
    server = socketserver.TCPServer((HOST, PORT),Myserver)
    # 让server永远运行下去,除非强制停止程序
    server.serve_forever()
# client 端
import socket

HOST, PORT = "127.0.0.1", 9999
data = "hello"

# 创建一个socket链接,SOCK_STREAM代表使用TCP协议
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect((HOST, PORT))          # 链接到客户端
    sock.sendall(bytes(data + "\n", "utf-8")) # 向服务端发送数据
    received = str(sock.recv(1024), "utf-8")# 从服务端接收数据

print("Sent:     {}".format(data))
print("Received: {}".format(received))

二.threading

线程初识

import time
import threading

def task(a1,a2,a3):
    time.sleep(2)
    print(拿快递)

def play():
    print(和女朋友去耍)

def wm():
    print(去拿外卖)

# 创建一个线程
# 让该线程去执行任务:函数
t1 = threading.Thread(target=task,args=(1,2,3,))
# 去执行吧
t1.start()

# 创建一个线程
# 让该线程去执行任务:函数
t2 = threading.Thread(target=play)
# 去执行吧
t2.start()
# 创建一个线程
# 让该线程去执行任务:函数
t3 = threading.Thread(target=wm)
# 去执行吧
t3.start()

print(玩扇子)
print(煽风点火)
print(耍贱...)

线程接收任务

import time
import threading
def task(n):
    print(开始执行任务:,n)
    time.sleep(10)
    print(...)
    print(任务%s 执行完毕:%n)

while True:
    name = input("请输入任务:")
    t = threading.Thread(target=task,args=(name,))
    t.start()

socket和线程配合

import time
import socket
import threading

def task(conn):
    time.sleep(20)
    data = conn.recv(1024)
    print(data)
    conn.close()


server = socket.socket()
server.bind((192.168.13.84,8001,))
server.listen(5)

while True:
    conn,addr = server.accept()
    t = threading.Thread(target=task,args=(conn,))
    t.start()

 

socketserver,threading

标签:strong   wro   elf   朋友   while   threading   强制   font   strip()   

原文地址:https://www.cnblogs.com/zwq-/p/9601086.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!