6
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-04-19

マルチスレッド処理をして、サブのスレッドがサーバとなって、メインスレッドからの入力を受け付けるようになっています。
ターミナル上で実行したのち、適当な文字列を打って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()
    
6
14
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?