Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8916603
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T05:16:37+00:00 2026-06-15T05:16:37+00:00

I am working on a chat program. I have a server and client, multiple

  • 0

I am working on a chat program. I have a server and client, multiple users can connect to the server. Currently, I just have the server send back whatever message the clients send to the server. I would like to add on an authentication so that I can accept/decline the connection if the authentication fails.

client:

class Network:
    # initialize the socket
    def __init__(self, client, host=host, port=port):
        self.client = client;
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
        self.port = port;
        self.host = host;
        self.addr = (host, port);

    # conenct to the server
    def connect(self):
        self.socket.connect(self.addr);

    # receive data from server if there is any
    def read(self):
        while True:
            time.sleep(0.1)
            try:
                data = self.socket.recv(1024);
            except:
                break;
                # instead of breaking, create "connection lost" then open the login form again
            print "in client: ", data;
            data_split = data.split("\r\n");
            for ds in data_split:
                self.client.msgbox.addMsg(ds);

    # send chat message to the server
    def send(self, msg):
        self.socket.send(msg);

    # authenticate user
    # if
    def authenticate(self, info):
        self.socket.send(info);

server:

class Server:
    # init the socket
    def __init__(self, host=host, port=port):
        self.host = host;
        self.port = port;
        self.addr = (host, port);
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);

    # send data to client
    def send(self, soc, data):
        try:
            soc.send(data);
        except:
            return "couldn't send message";

    # receive data from client
    def receive(self, soc):
        while True:
            try:
                return soc.recv(size);
            except:
                return disconnect;

    # connect client
    def connect(self):
        self.socket.bind(self.addr);
        self.socket.listen(5);
        self.socket_s = [self.socket];
        self.read_socs = [self.socket];
        self.write_socs = [];
        self.user_addr = {};

    # validate the user
    def validate(self, username, password):
        if username in users:
            sha = s256.new();
            sha.update(password);
            password = sha.hexdigest();

            if password == users[username]:
                print "in server: true";
                return True;
            else:
                print "in server: false";
                return False;

    # server
    def serve(self):
        while True:
            r_socs, w_socs, exceptions = select.select(self.read_socs, [], []);
            for s in r_socs:
                if s in self.socket_s:
                    print "accepting socket connect";
                    soc, address = s.accept();
                    print "in server: ", soc, address;
                    self.read_socs.append(soc);
                    self.write_socs.append(soc);
                    for ws in self.write_socs:
                        self.send(ws, "len(users) == " + str(len(self.write_socs)) + "\n");
                        print connection;
                else:
                    data = self.receive(s);
                    print "in server: " + data;
                    if auth in data:
                        ds = data.split(" ");
                        res = self.validate(ds[1], ds[2]);
                    elif data == disconnect:
                        s.close();
                        self.read_socs.remove(s);
                        self.write_socs.remove(s);
                        for ws in self.write_socs:
                            print "in server: " + ws
                            self.send(ws, "len(users) == " + str(len(self.write_socs)) + "\n");
                    else:
                        for ws in self.write_socs:
                            print "in server: " + ws;
                            self.send(ws, data);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T05:16:38+00:00Added an answer on June 15, 2026 at 5:16 am

    Your design is not actually going to work, because the data in a TCP message received doesn’t necessarily correlate with a single send from the other side—it could be half a message, or 3 messages, or 5-1/2 messages. If you’re just testing on localhost, with small messages, it will often seem to work in your tests, and then completely fail when you put it on the internet. That’s why you need to build some kind of protocol on top of TCP that uses delimiters (like newlines), length prefixes (like netstrings), or self-delimiting objects (like JSON).

    At any rate, you know the socket each message comes in on. You can map sockets to users, or just use the sockets themselves, or their fds, to make decisions. So, just as you keep track of all the known sockets to pass to select, you also keep track of all sockets known to be authenticated. If the socket a message comes in on is in that list, it’s authenticated; otherwise, the message is rejected unless it’s an auth message.

    Let’s say you’ve got a simple line protocol:

    def __init__(self):
        self.sockets = [] # add clients here, along with listener
        self.authsockets = [] # add authenticated clients here
        self.buffers = defaultdict(str)
    
    def loop(self):
        r, w, x = select.select([sockets], [sockets], [sockets])
        for sock in r:
            buffers[sock] = buffers[sock] + sock.recv(4096)
            lines = buffers[sock].split('\n')
            if buffers[sock][-1] != '\n':
                buffers[sock], lines = lines[-1], lines[:-1]
            else:
                buffers[sock] = ''
            for line in lines:
                processCommand(sock, line)
        # etc.
    
    def processCommand(self, sock, command):
        if self.isAuthCommand(command):
            if self.isValidAuthCommand(command):
                self.authsockets.append(sock)
            return
        if not sock in self.authsockets:
            return # ignore commands before auth
        self.doNormalThing(command)
    

    I’ve stripped out all of the irrelevant stuff—handling accepts, disconnects, errors, writes, etc. But you’ve got a similar problem there to your reads. First, you’re assuming that sockets are always writable, which is not true. You need to queue up a write buffer for each socket, and write when select tells you it’s OK. Again, this may seem to work on localhost, but it will fall apart on the internet. Second, writing to a socket may not send the entire buffer, so you need to look at how many bytes got written and keep buffer[bytecount:] around until next time.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been working on a (relatively) simple tcp client/server chat program for my
I'm working on a chat program where the client is single-threaded but the server
i have a java chat server & client, that works fine. I made a
I am working on a VERY SIMPLE chat client and server and I need
I am working on a C# chat client that needs to have a sending
I'm working on a remote chat server. When I open the chat(client side) how
I'm working on chat application. The underlying server uses Node.js and the client/server communication
I just started learning nodejs. I am currently working with sockets and made chat
Hey guys, I was working on a simple chat program to brush up on
i am working on a chat application. I am able to send and receive

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.