(Newbie) Help with sockets.

mentaltruckdriver at gmail.com mentaltruckdriver at gmail.com
Fri Feb 29 03:20:26 CET 2008


Hi everyone. I'm fairly new to Python, and even more new to socket
programming. I think I've wrapped my head around sockets, and with
that I want to create a Telnet-based chat server, the idea being
people connect to the telnet servers with their clients and they all
communicate. I've got the code working, but the server sends each
letter to the clients on a new line! I've read about this kind of
thing on Windows on Google, but I can't find a solution to this issue.

I got the code from here - http://www.scribd.com/doc/134861/Sockets-Programming-with-python.
When I get this working I want to take my knowledge of sockets and
expand the code further.

Here's the code:

import socket
import select

class ChatServer:

    def __init__( self, port ):
        self.port = port;

        self.srvsock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
        self.srvsock.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
        self.srvsock.bind(("", port))
        self.srvsock.listen( 5 )

        self.descriptors = [self.srvsock]
        print "ChatServer started, listening on port %s" % port

    def run( self ):
        while 1:
            (sread, swrite, sexc) = select.select( self.descriptors,
[], [] )
            for sock in sread:
                if sock == self.srvsock:
                    self.accept_new_connection()
                else:
                    data = ''
                    string = sock.recv(100)
                    if string == '':
                        host,port = sock.getpeername()
                        string = 'Client left %s:%s\r\n' % (host,
port)
                        self.broadcast_string( string, sock )
                        sock.close
                        self.descriptors.remove(sock)
                    else:
                        host, port = sock.getpeername()
                        newstring = '[%s:%s] %s\r\n' % (host, port,
string)
                        self.broadcast_string( newstring, sock )

    def accept_new_connection( self ):

        newsock, (remhost, remport) = self.srvsock.accept()
        self.descriptors.append( newsock )

        newsock.send("You're connected to the chat server!\r\n")
        string = 'Client joined %s:%s\r\n' % (remhost, remport)
        self.broadcast_string( string, newsock)

    def broadcast_string( self, string, omit_sock ):

        for sock in self.descriptors:
            if sock != self.srvsock and sock != omit_sock:
                sock.send(string)
        print string

server = ChatServer( 2626 ).run()

Can anyone help me find a solution to this? Any help would be
appreciated.

Thanks!



More information about the Python-list mailing list