python兩個子執行緒通過queue通訊

神棍先生發表於2017-12-21

版權宣告:本文可能為博主原創文章,若標明出處可隨便轉載。 https://blog.csdn.net/Jailman/article/details/78864046

SocketServer端程式碼

#!/usr/bin/env python

import threading
import SocketServer
import time
import queue

q = queue.Queue()


class MyHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        while True:
            data = self.request.recv(1024)
            # print data,self.client_address
            q.put(data)
            self.request.send(` %s %s ` % (data, time.ctime()))
            if data == `exit`:
                break


class SocketServer_Thread(threading.Thread, MyHandler):
    def __init__(self, Host, Port):
        super(SocketServer_Thread, self).__init__()
        self.host = Host
        self.port = Port

    def run(self):
        s = SocketServer.ThreadingTCPServer((self.host, self.port), MyHandler)
        s.serve_forever()


def run_socketserver(Host, Port):
    ss_thread = SocketServer_Thread(Host, Port)
    ss_thread.start()


class Message_Thread(threading.Thread):
    def run(self):
        while True:
            if not q.empty():
                message = q.get()
                print message


def run_messageoutput():
    mo_thread = Message_Thread()
    mo_thread.start()


if __name__ == "__main__":
    Host = `0.0.0.0`
    Port = 9999
    run_socketserver(Host, Port)
    run_messageoutput()

client端程式碼

#!/usr/bin/env python

import socket

HOST = `10.9.3.132`
PORT = 9999

s = socket.socket()
s.connect((HOST, PORT))
while True:
    kel = raw_input(`>>>`)
    s.sendall(kel)
    print s.recv(1024)
    if kel == `exit`:
        break
s.close()


相關文章