0

hey i'm working on a chat app and can't get any further at this point. The different clients connect to the server and can send messages successfully. But only the message from one client is displayed and not the message from the second one.

import socket
import _thread

s = socket.socket()
host = socket.gethostname()
print("Server wird auf folgendem Host gestartet: ", host)
port = 8080
s.bind(('127.0.0.1', 50010))
s.listen()
print("Server erfolgreich verbunden")
print("Server wartet auf Verbindungen...")


def serverlisten():
    while True:
        s.listen()
        conn, addr = s.accept()
        print(addr, " hat sich mit dem Server verbunden und ist online")

_thread.start_new_thread(serverlisten, ())

conn, addr = s.accept()
print(addr, " hat sich mit dem Server verbunden und ist online")


while True:
    incoming_message = conn.recv(1024)
    incoming_message = incoming_message.decode()
    print(addr, incoming_message)

1 Answers1

0

First you need to decide what connection type you plan to use: For a simple chat application I suggest UDP. The diiference between SOCK_DGRAM (UDP) and SOCK_STREAM (TCP) is explained here: What is SOCK_DGRAM and SOCK_STREAM?

import socket

port = 50010
s = socket(AF_INET, SOCK_DGRAM)
# reuse the port otherwise it will be blocked if the connection is not closed
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 
s.bind(('127.0.0.1',port))

Now there is no reason to use the s.accept and s.listen functions as the following function already does all that is needed:

while True:
try:
    data,addr = s.recvfrom(512) # number of bytes in the message
    msg = data.decode('utf-8')
    # here you can start a thread if multiple users connect simultaneously 
    time.sleep(0.001)
    
except KeyboardInterrupt:
    print('closed by Keyboard Interrupt')
    sock.close()

This is a functioning python UPD server. But not a messenger app as messages are only received. If you want a messenger application you need a server and a client on both sides of the communication.

    cmdOut = "Hello other side of the communication"
    byteOut = bytes(cmdOut.encode("utf-8"))     # Convert Server reply to bytes    
    s.sendto(byteOut,otherIP) # Send Server Reply back

I suggest using different ports on each side of the communication.

BastHut
  • 90
  • 6