Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Socket - Send/Receive messages at the same time

Basically I have been working on a simple chat room using socket and thread. In my client I can receive and send messages, my issue is that one comes before another in a loop, so if I am sending a message I will only receive data once I have sent a message. I want it to work like any other chat room, where I could receive a message when I am sending a message, any help will help greatly. This is my basic client:

import socket
import sys

###########
HOST = '25.0.18.52'
PORT = 9999
###########

name = input("Enter your name: ")
s = socket.socket()
s.connect((HOST,PORT))

while 1:
    message = input("Message: ")
    s.send("{}: {}".format(name, message).encode('utf-8'))
    data = s.recv(1024)
    a = data.decode("utf-8") 
    print(a)
like image 217
Satyrs Avatar asked Oct 30 '15 10:10

Satyrs


People also ask

Can a python socket send and receive at the same time?

You can send and receive on the same socket at the same time (via multiple threads). But the send and receive may not actually occur simultaneously, since one operation may block the other from starting until it's done. That is how it's in Winsock.

Can TCP send and receive at the same time?

TCP is bidirectional. There are actually two halves of a pipe created between client and server; think of this as being a full-duplex operation in that both sides of the conversation can send and receive simultaneously.

How does Python socket recv work?

The recv method receives up to buffersize bytes from the socket. When no data is available, it blocks until at least one byte is available or until the remote end is closed. When the remote end is closed and all data is read, it returns an empty byte string.


1 Answers

You should keep 2 threads: one for listening and the other for receiving. In your while loop, you should remove the listener part, and keep the code in a different thread. This way you can receive and type on the console at the same time.

def recv():
    while True:
         data = s.recv(1024).decode()
         if not data: sys.exit(0)
         print data

Thread(target=recv).start()
like image 130
Sugam Avatar answered Oct 28 '22 12:10

Sugam