puttputt
puttputt

Reputation: 1269

Python Multithreading, run two functions at the same time

So I'm learning about socket programming and have wrote a nifty little chat server. The problem I am having is that my client cannot read and write at the same time. I'm not too sure how to set this up.

This is what I have so far, I want read() and write() to be running concurrently (It isn't so much about reading and writing at the same time - it's about being able to receive messages while input() hangs waiting for user input.):

import socket 
import threading

class Client(threading.Thread):

    def __init__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(('127.0.0.1', 1234))
        print('Client connected to server')

        self.readThread = threading.Thread.__init__(self)
        self.writeThread = threading.Thread.__init__(self)

    def read(self):
        data = self.socket.recv(1024)
        if data:
            print('Received:', data)

    def write(self):
        message = input()
        self.socket.send(bytes(message, 'utf-8'))


client = Client()

while True:
    #do both

Upvotes: 2

Views: 3923

Answers (1)

g.d.d.c
g.d.d.c

Reputation: 47988

You're really close. Try something like this:

import socket 
import threading

class Client(threading.Thread):

    def __init__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(('127.0.0.1', 1234))
        print('Client connected to server')

        t = threading.Thread(target = self.read)
        t.daemon = True # helpful if you want it to die automatically
        t.start()

        t2 = threading.thread(target = self.write)
        t2.daemon = True
        t2.start()

    def read(self):
        while True:
            data = self.socket.recv(1024)
            if data:
                print('Received:', data)

    def write(self):
        while True:
            message = input()
            self.socket.send(bytes(message, 'utf-8'))


client = Client()

It's worth pointing out that if you're reading and writing from a single terminal this way your prompt could get a little out of hand. I imagine though that you're starting with print statements, but will eventually collect data into other containers in your app.

Upvotes: 3

Related Questions