码迷,mamicode.com
首页 > 编程语言 > 详细

python3 单线程(gevent)实现并发的socket通讯

时间:2019-06-17 01:19:27      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:try   eve   客户   rip   connect   通讯   一个   strip   服务   

# -*- coding: utf-8 -*-
from gevent import monkey; monkey.patch_all()import gevent
from socket import *


def talk(conn):
    while 1:  # 循环通讯
        try:
            from_client_msg = conn.recv(1024)
            if not from_client_msg:break
            print("来自客户端的消息:%s" %(from_client_msg))
            conn.send(from_client_msg.upper())
        except:
            break
    conn.close()


if __name__ == __main__:
    server = socket()
    ip_port = ("127.0.0.1", 8001)
    server.bind(ip_port)
    server.listen(5)
    while 1:  # 循环连接
        conn, addr = server.accept()
        gevent.spawn(talk, conn)  # 开启一个协程
    server.close()
# -*- coding: utf-8 -*-
from socket import *


client = socket()
ip_port = ("127.0.0.1", 8001)
client.connect(ip_port)
while 1:  # 循环通讯
    inp = input(">>:").strip()
    if not inp: continue
    if inp.upper() == "Q": break
    client.send(inp.encode())
    from_server_msg = client.recv(1024)
    print("来自服务端的消息:", from_server_msg)
client.close()

 

python3 单线程(gevent)实现并发的socket通讯

标签:try   eve   客户   rip   connect   通讯   一个   strip   服务   

原文地址:https://www.cnblogs.com/lilyxiaoyy/p/11037487.html

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