多进程并行实现socket并发代码

服务端:

# Author:Winter Liu is coming!
import socket
from multiprocessing import Process


def func(conn,addr):
    print("{} is connect!".format(addr))
    try:
        while True:
            msg = conn.recv(1024).decode("utf-8")
            conn.send(msg.upper().encode("utf-8"))
    except ConnectionResetError:
        conn.close()
        print("{} is close!".format(addr))


# Windows系统下需要加验证
if __name__ == "__main__": server = socket.socket() server.bind(("127.0.0.1",10002)) server.listen() while True: conn, addr = server.accept()
     # 进程创建 p
= Process(target=func, args=(conn, addr)) p.start() # 异步非阻塞运行,交给操作系统执行进程,主进程继续执行

客户端:

# Author:Winter Liu is coming!
import socket
import time

client = socket.socket()
client.connect(("127.0.0.1", 10002))

while True:
    client.send("hello".encode("utf-8"))
    msg = client.recv(1024).decode("utf-8")
    print(msg)
    time.sleep(0.5)

client.close()

 

------------恢复内容开始------------

服务端:

# Author:Winter Liu is coming!
import socket
from multiprocessing import Process


def func(conn,addr):
    print("{} is connect!".format(addr))
    try:
        while True:
            msg = conn.recv(1024).decode("utf-8")
            conn.send(msg.upper().encode("utf-8"))
    except ConnectionResetError:
        conn.close()
        print("{} is close!".format(addr))


if __name__ == "__main__":
    server = socket.socket()
    server.bind(("127.0.0.1",10002))
    server.listen()

    while True:
        conn, addr = server.accept()
        p = Process(target=func, args=(conn, addr))
        p.start()

客户端:

# Author:Winter Liu is coming!
import socket
import time

client = socket.socket()
client.connect(("127.0.0.1", 10002))

while True:
    client.send("hello".encode("utf-8"))
    msg = client.recv(1024).decode("utf-8")
    print(msg)
    time.sleep(0.5)

client.close()

 

------------恢复内容结束------------

多进程并行实现socket并发代码

上一篇:跟高手学习LINUX笔记-25 --构建FTP服务器


下一篇:记录用linux命令踢掉远程登录用户