Python Chatroom: Sending messages while receving messages

Viewed 33

I have created two chatroom programs. The idea is that the server and client(s) can transfer messages between each other.

The current situation is that the server cannot receive messages whilst entering messages neither can client type messages whilst waiting for server to send.

I have been looking at threading to solve this problem but haven't got a clue to implement it.

Server code:

#Chatroom Server

import socket
import threading

host = socket.gethostname()
ip = socket.gethostbyname(host)
print('Host name:', host)
print('Host IP:' , ip)
port = 8080
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((ip,port))

name = input('Enter host name:')
s.listen(3)#Allows maximum 3 connections to server
conn,addr = s.accept()
print('Connection established with: ', addr[0])
client = (conn.recv(1024)).decode()
print(client + ' connected')
conn.send(name.encode())

while True:
    msg = input('You:')
    choice = False
    while True:
        choice = input('Do you want to enter another line? (Y/N)')
        if choice.upper() == 'Y':
            add_msg= input("You:")
            msg = msg + '\n' +add_msg
        else:
            break 
    conn.send(msg.encode())
    msg = conn.recv(1024)
    msg = msg.decode()
    print(client+':'+msg)

Client code:

#Chatroom Client

import socket

hip = 'xxx.xx.xx.xx' #hip = host ip
port =  8080
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((hip,port))

name = input('Enter username:')
s.send(name.encode())
hname = s.recv(1024)
hname = hname.decode()
while True:
    smsg = (s.recv(1024).decode())
    print(hname+':'+smsg)
    msg = input('You:')
    choice = False
    while True:
        choice = input('Do you want to enter another line? (Y/N)')
        if choice.upper() == 'Y':
            add_msg= input("You:")
            msg = msg + '\n' +add_msg
        else:
            break 
    s.send(msg.encode())
0 Answers
Related