zoukankan      html  css  js  c++  java
  • python3 在一个进程内开启多个线程实现socket通讯

    # -*- coding: utf-8 -*-
    import threading
    from socket import *
    from threading import Thread
    
    
    def talk(conn):
        while 1:  # 循环通讯
            try:
                from_client_msg = conn.recv(1024)
                if not from_client_msg:break
                print("线程<%s>来自客户端的消息:%s" %(threading.current_thread().getName(), from_client_msg))
                conn.send(from_client_msg.upper())
            except:
                break
        conn.close()
    
    
    if __name__ == '__main__':
        '''一个进程里开多线程实现socket通讯'''
        server = socket()
        ip_port = ("127.0.0.1", 8001)
        server.bind(ip_port)
        server.listen(5)
        while 1:  # 循环连接
            conn, addr = server.accept()
            t = Thread(target=talk, args=(conn,))
            t.start()
        server.close()
    
    
    # 线程<Thread-1>来自客户端的消息:b'aaa'
    # 线程<Thread-2>来自客户端的消息:b'bbb'
    # 线程<Thread-3>来自客户端的消息:b'ccc'
    # 线程<Thread-4>来自客户端的消息:b'dddd'
    # 线程<Thread-5>来自客户端的消息:b'eeee'
    # 线程<Thread-6>来自客户端的消息:b'ffff'
    # -*- 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()
  • 相关阅读:
    微信运营
    1.数据库&SQL语言
    16.线程
    15.IO流
    14.异常
    13.集合
    12.常用类
    11.String类-StringBuffer类、StringBuilder类
    10.Object类-包装类-内部类
    9.接口
  • 原文地址:https://www.cnblogs.com/lilyxiaoyy/p/11037505.html
Copyright © 2011-2022 走看看