多进程并发简单socket

时间:2024-06-23 12:33:20

server---------------------
这种简单实现:坏处客户端启动一个一个进程,进程多了机器要蹦
#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/17

from socket import *
from multiprocessing import Process

# 负责通信
def talk(conn):
    while True:
        try:
            data = conn.recv(1024)
            if not data: break
            conn.send(data.upper())
        except ConnectionResetError:
            break
    conn.close()

# 建立链接
def server(ip, port):
    server = socket(AF_INET, SOCK_STREAM)
    server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    server.bind((ip, port))
    server.listen(5)

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

if __name__ == '__main__':
    server('127.0.0.1', 8080)

client-------------------
#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/17

# 客户端可以启动多个进程,启动一个就是一个进程
from socket import *

client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8080))

while True:
    msg = input('>>>:').strip()
    if not msg: continue
    client.send(msg.encode('utf-8'))
    data = client.recv(1024)
    print(data.decode('utf-8'))