Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python client side in chat

I have a problem while trying to build the client side of a chat. I just in the begining, this is my code:

import socket
my_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
my_socket.connect(("10.10.10.69",1234))
while True:
    message=raw_input("your message: ")
    if(message=="quit"):
        my_socket.close()
        break
    my_socket.send(message)
    data=my_socket.recv(1024)
    print "message from server:" , data

The problem is the raw_input. When a user sends a message the other users are stacked on the raw_input so only when they sends a message too they get the new messages.

How can I fix it (without using threads)?

like image 831
Nityuiop18 Avatar asked May 15 '26 18:05

Nityuiop18


1 Answers

As I commented, use select.select if your chat client is running in Unix.

For example:

import socket
import sys
import select

my_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
my_socket.connect(("10.10.10.69",1234))
sys.stdout.write('your message: ')
sys.stdout.flush()
while True:
    r, w, x = select.select([sys.stdin, my_socket], [], [])
    if not r:
        continue
    if r[0] is sys.stdin:
        message = raw_input()
        if message == "quit":
            my_socket.close()
            break
        my_socket.send(message)
        sys.stdout.write('your message: ')
        sys.stdout.flush()
    else:
        data = my_socket.recv(1024)
        print "message from server:" , data
like image 123
falsetru Avatar answered May 18 '26 06:05

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!