Ad

How To Receive Messages Without Pressing Enter In Socket Programming

- 1 answer

I'm new to socket programming in Python and I'm trying to write a chatroom application, but I have a problem which is it each client should press enter in order to receive messages from other clients.

#my client side code
import socket 
import sys

client_sock = socket.socket() 
port = int(sys.argv[1])
client_sock.connect(('127.0.0.1', port))
print("Connected to server. start sending messages") 
while True:
    sending_message = input('> ')
    if sending_message:
        client_sock.send(sending_message.encode())
    receiving_message = client_sock.recv(1024)
    if  receiving_message:
        print(receiving_message.decode()) 
Ad

Answer

input pauses your program. Thus, either you can't use input blindly, or you have to use threads. Using threads is easier than the alternative (using select to figure out what to do next). Have one thread for input and sending, one thread for receiving and printing.

Here's a trivial rewrite of your code:

import threading
import socket 
import sys

client_sock = socket.socket() 
port = int(sys.argv[1])
client_sock.connect(('127.0.0.1', port))
print("Connected to server. start sending messages")

def sender():
    while True:
        sending_message = input('> ')
        if sending_message:
            client_sock.send(sending_message.encode())

def receiver():
    while True:
        receiving_message = client_sock.recv(1024)
        if  receiving_message:
            print(receiving_message.decode()) 

sender_thread = threading.Thread(target=sender)
receiver_thread = threading.Thread(target=receiver)

sender_thread.start()
receiver_thread.start()

sender_thread.join()
receiver_thread.join()
Ad
source: stackoverflow.com
Ad