1

I'm trying to write code for a chat server using sockets for multiple clients. But it is working for only a single client. Why is it not working for multiple clients?

I have to perform this program using Beaglebone Black. My server program will be running on beaglebone and normal clients on gcc or terminal. So I can't use multithreading.

    #SERVER                                                                      
import socket
import sys

s=socket.socket()
s.bind(("127.0.0.1",9998))
s.listen(10)

while True:
    sc,address = s.accept()
    print address
    while True:
            msg = sc.recv(1024)
        if not msg:break


        print "Client says:",msg
        reply = raw_input("enter the msg::")
        sc.send(reply)  
    sc.close()
s.close()

#CLIENT
import socket
import sys
s= socket.socket()
s.connect(("127.0.0.1",9998))

while (1):
    msg = raw_input("enter the msg")
    s.send(msg)
    reply = s.recv(1024)
    print "Server says::",reply
s.close()
KillianDS
  • 16,936
  • 4
  • 61
  • 70
Pankaj Andhale
  • 401
  • 9
  • 24
  • Use threads, that'll help – ForceBru Apr 09 '15 at 12:08
  • 1
    possible duplicate of [Python Socket Multiple Clients](http://stackoverflow.com/questions/10810249/python-socket-multiple-clients) – legoscia Apr 09 '15 at 12:12
  • 4
    @ForceBru he might take your advice seriously. I don't think SO is a place for cruel jokes – user3159253 Apr 09 '15 at 12:16
  • 2
    @legoscia might not be a duplicate, the code as posted should actually work fine for multiple clients, just not for multiple *simultaneous* clients, which might be the OP's actual request. – KillianDS Apr 09 '15 at 12:48

1 Answers1

2

Use an event loop.

Integrated in python like asyncio : Echo server example

or use an external library that provides the event loop like libuv: Echo server example.

Note: Your code is not working for multiple clients simultaneously beacause you are blocked in the receive operation and you are not handling new accept operations.