Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple telnet chat server in Python

I was reading about sockets and found a nice exercise to try: a simple chat server that echoes input. This appears to be a common exercise and I have found several examples such as chatserver5.py and some SO questions. The problem is I can only connect when using telnet localhost 51234 and not telnet 192.168.1.3 51234 (where 192.168.1.3 is the network IP of my "server"). Needless to say, I can't connect from another machine on my network. I get the following output:

Trying 192.168.1.3...
telnet: connect to address 192.168.1.3: Connection refused
telnet: Unable to connect to remote host

Here is my code:

import socket, threading

HOST = '127.0.0.1'
PORT = 51234 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)
clients = [] #list of clients connected
lock = threading.Lock()


class chatServer(threading.Thread):
    def __init__(self, (socket,address)):
        threading.Thread.__init__(self)
        self.socket = socket
        self.address= address

    def run(self):
        lock.acquire()
        clients.append(self)
        lock.release()
        print '%s:%s connected.' % self.address
        while True:
            data = self.socket.recv(1024)
            if not data:
                break
            for c in clients:
                c.socket.send(data)
        self.socket.close()
        print '%s:%s disconnected.' % self.address
        lock.acquire()
        clients.remove(self)
        lock.release()

while True: # wait for socket to connect
    # send socket to chatserver and start monitoring
    chatServer(s.accept()).start()

I have no experience with telnet or sockets. Why I can't connect remotely and how can I fix it so I can?

like image 808
styfle Avatar asked Jun 27 '11 01:06

styfle


1 Answers

If you set HOST = '', then you'll be able to connect from anywhere. Right now, you're binding it to 127.0.0.1, which is the same as localhost.

like image 158
Ravi Avatar answered Sep 20 '22 16:09

Ravi