Multi-thread processing is performed, and the sub thread becomes the server and accepts the input from the main thread. After executing it on the terminal, type an appropriate character string and press the Enter key, and the character string will be sent from the main thread to the sub thread by socket communication. When the subthread receives the string, it is printed to the terminal by the print statement.
environment ・ 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) #This is too long (command to wait 100 seconds)
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()
Recommended Posts