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 8210561
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T10:06:47+00:00 2026-06-07T10:06:47+00:00

I’ve been trying to code a simple chat server in Python, my code is

  • 0

I’ve been trying to code a simple chat server in Python, my code is as follows:

import socket
import select

port = 11222
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1024)
serverSocket.bind(('',port))
serverSocket.listen(5)

sockets=[serverSocket]
print 'Server is started on port' , port,'\n'

def acceptConn():
    newsock, addr = serverSocket.accept()
    sockets.append(newsock)
    newsock.send('You are now connected to the chat server\n')
    msg = 'Client joined',addr.__str__(),
    broadcast(msg, newsock)

def broadcast(msg, sourceSocket):
    for s in sockets:
        if (s != serverSocket and s != sourceSocket):
            s.send(msg)
    print msg,


while True:
    (sread, swrite, sexec)=select.select(sockets,[],[])
    for s in sread:
        if s == serverSocket:
            acceptConn()
        else:
            msg=s.recv(100) 
            if msg.rstrip() == "quit":
                host,port=socket.getpeername()
                msg = 'Client left' , (host,port)
                broadcast(msg,s)
                s.close()
                sockets.remove(s)
                del s
            else:
                host,port=s.getpeername()
                msg = s.recv(1024)
                broadcast(msg,s)
                continue

After running the server and connecting via telnet, the server reads single character and skips the next one. Example if I type Hello in telnet, server reads H l o.
Any help please ?! 🙂

  • 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-07T10:06:49+00:00Added an answer on June 7, 2026 at 10:06 am

    You call recv twice.

    First:

    msg=s.recv(100)
    

    Then, if that’s not “quit”, you read and broadcast another message:

    msg = s.recv(1024)
    broadcast(msg,s)
    

    So the original message is lost.

    Because you’re using telnet as the client, you get one character at a time, so you see every other character. If you used, say, nc instead, you’d get different results—but still the same basic problem of every other read being thrown away.

    There are a few other problems here:

    • You’re expecting clients to send “quit” before quitting—you should be handling EOF or error from recv and/or passing sockets in the x as well as the r.
    • You’re assuming that “quit” will always appear in a single message, and an entire message all to itself. This is not a reasonable assumption with TCP. You may get four 1-byte reads of “q”, “u”, “i”, and “t”, or you may get a big read of “OK, bye everyone\nquit\n”, neither of which will match.
    • The “Client left” and “Client joined” messages are tuples, not strings, and they’re formed differently, so you’re going to see (‘Client joined’, “(‘127.0.0.1’, 56564)”) (‘Client left’, (‘127.0.0.1’, 56564)).
    • You’re relying on the clients to send newlines between their messages. First, as mentioned above, even if they did, there’s no guarantee that you’ll get complete/discrete messages. Second, your “system” messages don’t have newlines.

    Here’s a modified version of your sample that fixes most of the problems, except for requiring “quit” to be in a single message alone and relying on the clients to send newlines:

    #!/usr/bin/python
    
    import socket
    import select
    import sys
    
    port = 11222
    serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1024)
    serverSocket.bind(('',port))
    serverSocket.listen(5)
    
    sockets=[serverSocket]
    print 'Server is started on port' , port,'\n'
    
    def acceptConn():
        newsock, addr = serverSocket.accept()
        sockets.append(newsock)
        newsock.send('You are now connected to the chat server\n')
        msg = 'Client joined: %s:%d\n' % addr
        broadcast(msg, newsock)
    
    def broadcast(msg, sourceSocket):
        for s in sockets:
            if (s != serverSocket and s != sourceSocket):
                s.send(msg)
        sys.stdout.write(msg)
        sys.stdout.flush()
    
    
    while True:
        (sread, swrite, sexec)=select.select(sockets,[],[])
        for s in sread:
            if s == serverSocket:
                acceptConn()
            else:
                msg=s.recv(100)
                if not msg or msg.rstrip() == "quit":
                    host,port=s.getpeername()
                    msg = 'Client left: %s:%d\n' % (host,port)
                    broadcast(msg,s)
                    s.close()
                    sockets.remove(s)
                    del s
                else:
                    host,port=s.getpeername()
                    broadcast(msg,s)
                    continue
    

    To fix the ‘quit’ problem, you’re going to have to keep a buffer for each client, and do something like this:

    buffers[s] += msg
    if '\nquit\n' in buffers[s]:
       # do quit stuff
    lines = buffers[s].split('\n')[-1]
    buffers[s] = ('\n' if len(lines) > 1 else '') + lines[-1]
    

    But you’ve still got the newline problem. Imagine that user1 logs in and types “abc\n” while user2 logs in and types “def\n”; you may get something like “abClient joined: 127.0.0.1:56881\ndec\nf\n”.

    If you want a line-based protocol, you have to rewrite your code to do the echoing on a line-by-line instead of read-by-read basis.

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

Sidebar

Related Questions

I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
I have this code to decode numeric html entities to the UTF8 equivalent character.
I am trying to render a haml file in a javascript response like so:

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.