Help us understand the problem. What is going on with this article?

Pythonによるソケット通信とマルチスレッド処理

More than 1 year has passed since last update.

マルチスレッド処理をして、サブのスレッドがサーバとなって、メインスレッドからの入力を受け付けるようになっています。
ターミナル上で実行したのち、適当な文字列を打ってEnterキーを押すと、メインスレッドからサブスレッドへとソケット通信によって文字列が送られます。
サブスレッドのほうで文字列を受け取ると、print文により、ターミナルに出力されます。

環境
・Python2.7

thread_socket.py
import threading
import socket
import time
import datetime


# for receiving
class TestThread(threading.Thread):
    def __init__(self):
        super(TestThread, self).__init__()

        self.host = ""
        self.port = 12345
        self.backlog = 10
        self.bufsize = 1024

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind((self.host, self.port))

    def run(self):
        print " === sub thread === "
        self.sock.listen(self.backlog)
        conn, address = self.sock.accept()
        while True:
            mes = conn.recv(self.bufsize)
            if mes == 'q':
                print "sub thread is being terminaited"
                break
            print mes

        self.sock.close()


if __name__ == '__main__':
    th = TestThread()
    th.setDaemon(True)
    th.start()

    time.sleep(1)
    # time.sleep(100)  # これは長すぎる(100秒待て、という指令)

    print " === main thread === "

    ip = "localhost"
    port = 12345
    bufsize = 1024

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    while True:
        inp = raw_input("YOU>")
        sock.send(inp)
        time.sleep(1)
        if inp == 'q':
            th.join()
            print "main thread is being terminated"
            break

    sock.close()

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away