G.yx
G.yx

Reputation: 673

why python multithreading doesn't work in socket when sending message to server?

I'm try to grab bullet screens by python. The process is that I will get the response after sending login and some others messages to bullet screens server.

When I plan to grab two rooms's bullet screens, I can only get the response of the first request.

Code is like this:

# coding=utf-8

import multiprocessing
import socket
import time
import re
import signal
import threading



client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname("openbarrage.douyutv.com")
port = 8601
client.connect((host, port))

def send_req_msg(msg):
    """
    wrap msg
    """
    pass

def set_msg(roomid):
    msg = 'type@=loginreq/roomid@={}/\0'.format(roomid)
    send_req_msg(msg)

    msg_more = 'type@=joingroup/rid@={}/gid@=-9999/\0'.format(roomid)
    send_req_msg(msg_more)



if __name__ == '__main__':
    pool = []
    roomid = [123, 666]
    for i in range(0, len(roomid)):
        t = threading.Thread(target=set_msg(roomid[i]))
        t.start()
        pool.append(t)
    for a in pool:
        a.join()

Both multiprocessing and threading can't succeed. As I use wireshard to analysis the tcp. There is only the first request and it's response. Also I can only get the room's screen bullets of 123. So why the second thread/processing doesn't work? And what should I do? Thanks.

Upvotes: 0

Views: 511

Answers (1)

Kevin
Kevin

Reputation: 30161

t = threading.Thread(target=set_msg(roomid[i]))

This does not pass the function set_msg() to the thread. It calls the function and passes the result to the thread (in this case, the value passed is always None because set_msg() does not return anything). If you call the function before creating the thread, then the function will not run in the thread. You need to pass the function (and its arguments) to the Thread constructor without calling it:

t = threading.Thread(target=set_msg, args=(roomid[i],))

Upvotes: 2

Related Questions