Python socket: Chat server does not work properly

A

ARD

Guest
I'm working in a chat server with Python sockets and threading, where you can communicate between two computers. When you want to send a message, you send it to the server, and then the server sends it to the other computer.

I've searched through the Internet and found that socket can have problems when working with threading, so I tried to use threading's Lock() class. However, I don't know how to use it in my code.

Here's the server code:

import socket
import threading

def loop1():
while True:
data = conn1.recv(1024)
conn2.send(data)

def loop2():
while True:
data = conn2.recv(1024)
conn1.send(data)

host = "" #The host adress
port = 9696

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(2)

conn1, addr1 = s.accept()
print("Connection 1")
conn2, addr2 = s.accept()
print("Connection 2")

thread1 = threading.Thread(target = loop1)
thread2 = threading.Thread(target = loop2)

while True:
pass


Here's the client code:

import socket
import threading


def send():
while True:
missatge = input('Jo: ')
s.send((name + ': ' + missatge).encode('utf-8'))

def recieve():
while True:
dades = s.recv(1024)

print(dades.decode('utf-8'))

name = input("Nom: ")

host = "" #The host adress
port = 9696

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected")


thread1 = threading.Thread(target = send)
thread2 = threading.Thread(target = recieve)

thread1.start()
thread2.start()

while True:
pass


I want both clients to be able to send their messages through an input() in a while loop, at he same time that they receive the messages that the other client is sending. I thought the code above would work, but it doesn't. However, I tried to write a code where one client sent the messages and the other received them, and it worked. What do I have to change to make it work as I want?

Thanks for your help.

Continue reading...
 
Top