python socket通信 多线程实现

服务端

# coding=utf-8


import threading
import socket

socket_list = []

s = socket.socket()
s.bind(('172.30.213.238', 3000))
s.listen()


def read_from_client(s):
    try:
        return s.recv(1024).decode('utf-8')
    except:
        # 如果异常的话可能就是会话中断 那么直接删除
        socket_list.remove(s)


def server_target(s):
    try:
        while True:
            content = read_from_client(s)
            print(content)
            if content is None:
                break
            for client_s in socket_list:
                client_s.send(content.encode('utf-8'))

    except IOError as e:
        print(e.strerror)


while True:
    c, addr = s.accept()  # 一直等待客户端的连接
    socket_list.append(c)  # 如果收到则加到列表中
    threading.Thread(target=server_target, args=(c,)).start()

客户端:

# coding=utf-8

import socket
import threading

s = socket.socket()
s.connect(('172.30.213.238', 3000))


def receice_from_server(s):
    while True:
        print(s.recv('1024').decode('utf-8'))


threading.Thread(target=receice_from_server, args=(s,))
while True:
    line = input('')
    if line is None or line == 'exit':
        break
    s.send(line.encode('utf-8'))

python socket通信 多线程实现_第1张图片

你可能感兴趣的:(python)