• day29 作业


    写一个基于TCP协议套接字,服务端实现接收客户端的连接并发。

    多线程

    #客户端
    import socket
    
    client=socket.socket()
    client.connect(('127.0.0.1',8888))
    # def c():
    while True:
        s = input('输入:')
        client.send(s.encode('utf-8'))
        data=client.recv(1024).decode('utf-8')
        print(data)
    client.close()
    #服务端
    import socket
    from threading import Thread
    def s(conn):
        while True:
            try:
                data=conn.recv(1024).decode('utf-8')
                print(data)
                conn.send(data.encode('utf-8'))
            except Exception as e:
                print(e)
                break
        conn.close()
    
    if __name__ == '__main__':
        # while True:
        server = socket.socket()
        server.bind(('127.0.0.1', 8888))
        server.listen()
        while True:
            conn,addr=server.accept()
            t=Thread(target=s,args=(conn,))
            t.start()
    
    

    多进程

    #客户端
    import socket
    
    client=socket.socket()
    client.connect(('127.0.0.1',9999))
    while True:
        data=input('客户端输入:')
        client.send(data.encode('utf-8'))
        msg=client.recv(1024).decode('utf-8')
        print(msg)
    #服务端
    import socket
    from multiprocessing import Process
    def s(conn):
        while True:
            try:
                data=conn.recv(1024).decode('utf-8')
                print(data)
                conn.send(data.encode('utf-8'))
            except Exception as e:
                print(e)
                break
        conn.close()
    if __name__ == '__main__':
        server=socket.socket()
        server.bind(('127.0.0.1',9999))
        server.listen()
        while True:
            conn,addr=server.accept()
            t=Process(target=s,args=(conn,))
            t.start()
    
    
  • 相关阅读:
    并发队列、线程池、锁
    JVM、垃圾收集器
    Socket网络编程
    Netty入门
    SpringCloud微服务负载均衡与网关
    Android监听耳机按键事件
    利用本地不同磁盘文件夹作为git远程仓库进行灾备
    chrome浏览器form中button每点击一次,form就会提交一次
    [企业路由器] 一对一NAT映射设置指导
    win7镜像自带IE9的卸载
  • 原文地址:https://www.cnblogs.com/zqfzqf/p/11722294.html
Copyright © 2020-2023  润新知