Python 2.7 Tutorial Pt 18 Chat Server

Python PictureIn this Python Tutorial I show you how to build a simple chat server. All you need to do this are the pre-installed modules: asyncore, asynchat and socket.

The code then basically does the following:

  • Assigns a special address for each person that goes to the port (Socket)
  • Listens for any messages
  • When it gets a new message it sends it through the socket and into the port
  • A dispatcher decides what code should be called based off of the message sent


If you find this article helpful, please click here so more people can find this :)

Leave any questions or comments below and here are all of my previous Python Video Tutorial’s:

All the Code from the Video

#!/usr/bin/python

from asyncore import dispatcher
from asynchat import async_chat
import socket, asyncore

PORT = 5006
NAME = ‘ChatLine’

class ChatSession(async_chat):
def __init__(self,server,sock):
async_chat.__init__(self, sock)
self.server = server
self.set_terminator(“\r\n”)
self.data = []

def collect_incoming_data(self, data):
self.data.append(data)

def found_terminator(self):
line = ”.join(self.data)
self.data = []
self.server.broadcast(line)

def handle_close(self):
async_chat.handle_close(self)
self.server.disconnect(self)

class ChatServer(dispatcher):
def __init__(self, port, name):
dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((”,port))
self.listen(5)
self.name = name
self.sessions = []

def disconnect(self, sessions):
self.sessions.remove(session)

def broadcast(self, line):
for session in self.sessions:
session.push(‘>>’ + line + ‘\r\n’)

def handle_accept(self):
conn, addr = self.accept()
self.sessions.append(ChatSession(self, conn))

if __name__ == ‘__main__’:
s = ChatServer(PORT, NAME)
try: asyncore.loop()
except KeyboardInterrupt: print

68 Responses to “Python 2.7 Tutorial Pt 18 Chat Server”

  1. Tito says:

    Hi Derek,

    Thank you very much for all your hard work setting up all the tutorials. So far I have enjoyed every piece of the Python tutorials and I have to say that your ability to cope with many different fields ie. R&D, marketing, health, etc.. is really impressive. You must be gifted.

    Anyway, I am wondering if you could add the authentication piece to the chat server so the users will have to login and be authenticated against the local passwd file instead of telnet’ing directly into the server with the specified port.

    Thanks in advance,
    Tito

    • admin says:

      In the current tutorial I’m working on I’ll go more into how to use MySQL step by step. That should answer any questions you have in regards to how to implement that authentication. Glad you liked the tutorial :)

  2. Fred says:

    Hi! Great tutorial! You should definetly make more tutorials that cover netwoking in-depth! // Fred

  3. Musti says:

    The code don’t work

    • admin says:

      Sometimes there are encoding problems when you copy the code directly from the site. These can normally be fixed by changing all back quotes into normal quotes. If you want I can send you the original code. I’m positive it will work. Thanks

  4. Musti says:

    Yes please send it to me
    and I’m using win 7
    I can’t open any python file

  5. Musti says:

    Ok
    first thanks
    second what should I do to open the chat
    can you make a video for win 7 users
    can i use it from 2 different times at the same time

  6. Musti says:

    Sorry
    I mean from 2 different computers or laptops at the same time
    and will U make a tutorial how to open chat for windows users
    thankx

    • admin says:

      I’ll show you how to create a perfect chat system using Javascript very soon. It will be cross platform and easy to set up and style however you’d like. Hope that helps.

  7. Musti says:

    Can I then use it from 2 different computers?
    Will you make that tutorial as soon as possible , Will you also use Windows 7?
    Thanks in Advance

    • admin says:

      Yes it will work on numerous browsers at one no matter the operating system. I’ll include it in the new JavaScript tutorial which will follow the CSS tutorial which will be completed today or tomorrow

  8. Musti says:

    Oke Thanksin Advance
    Don’t forget to please use Windows 7.
    I have a Question:
    I need to program a script for topics, I will in the form let the admin choose like adding the topic on 11-02-2011. Can you give me a code?

  9. Mustix says:

    I don’t understand what you mean.

  10. Musti says:

    No the story about topics is another script,
    Did U finish the tutorial

  11. Musti says:

    Hello,
    Will you please answer me
    I need help
    How can i make a chat on my website and let just to people chat.
    Like facebook (Ex: derek,musti,php,html are online derek needs to chat with musti like php & html can’t see the content of the chat.
    Thanks
    Musti

    • admin says:

      I’ll be making one very soon, but I’m going to build it using PHP and JavaScript. I just find it easier to use those languages because very few hosting companies allow you to use Django with Python.

  12. Musti says:

    Hello,
    When are you going to make the tutorial?
    I’m waiting sorry for asking.
    Do you have a code or can you program it for me and send it by e-mail?
    Thanks

    • admin says:

      Which tutorial are you looking for. Sorry, but I’ve been kind of overwhelmed with comments and it has been hard to keep some requests in order

      • Musti says:

        No problem .
        My tutorial That i have asked was Chat script.
        How can i make a chat on my website and let just to people chat.?
        Like facebook (Ex: derek,musti,php,html are online derek needs to chat with musti like php & html can’t see the content of the chat.
        I hope you will make it
        Thanks

        • admin says:

          Yes I’m going to do that. I was confused because your userid was different. I’m going to be working on bigger projects now that I got the easier stuff done like chat, forums, wordpress stuff, etc. My next tutorial will be on a forum (message board) and then a chat system. I’m actually going to approach chat from a few different angles. A simple chat and then a more complicated huge chat system using Facebooks Tornado Server

  13. Musti says:

    Thanks,
    When are you going to start??

  14. Dhaval says:

    I am really looking forward to any new videos u will upload .. :)
    u rock big time .. :)

  15. kasi6713 says:

    Could you post some tutorial on some concepts like decorator,threading etc in python?

  16. Harry says:

    Can u please send me the code, i am having trouble using this. Like i get errors for def, for some reason.

  17. Articus says:

    Alright, I got a VERY odd error when running this code and I fixed it with an slight alter. I bring it up b/c it causes some really odd things on a Windows XP PC. RAM corruption is probably the best word I have for it.

    IN ChatServer -> IN def disconnect AND def broadcast
    Changed any point where it said session to sessions. I assume this was a typo, but caused some very interesting effects after closing it.

    • admin says:

      That’s very interesting. Python interpreters act differently depending on the OS, computer itself, etc. I normally stick to linux machines and stay away from pcs. It’s kind of a shame that everyone is taught to program on pcs even though most development in the real world is done on linux.

      • Articus says:

        No argument there, problem for me is I can’t get Linux to work on my PC. (Wireless won’t work, glitches out and have to delete Linux, etc.) My poor laptop hates Linux, heh.

        • admin says:

          Have you tried using wubi? It installs Ubuntu just like any other application on a PC.

          • Articus says:

            Yes, actually. That caused other issues, it would error and crash at 1% installing. (I need a new laptop.)

            • admin says:

              Wow yes it sounds like you have some problems. Definitely consider a mac next time. I don’t know of anyone making quality PCs anymore. Dell used to be reliable. HP uses the cheapest components and I know personally their warranty isn’t worth the paper it’s printed on

  18. Cyd says:

    Me again…

    Hi,

    In the ChatServer class, the disconnect method is giving me fits. We’re passing in “sessions”, but calling to remove “session” and so I get the error:

    NameError: global name ‘session’ is not defined

    Where is it supposed to be getting “session” from?

    Thanks,
    Cyd

    • admin says:

      Did you copy the code directly from the site? I just checked it and it worked for me. You get session from asyncore. These are all classes that come with predefined methods and variables.

      • KByte says:

        Hi, there is a little misstyping.
        Line 37 should look like that
        def disconnect(self, session):
        self.sessions.remove(session)

        second parameter is session not sessions

  19. khan says:

    i want to create an sms based chat services conacting my gsm modem to pc.my pc should run like 24/7 as server.and people can register through sms and make groups …an example site is this
    http://www.loop.pk

    • admin says:

      I’ll look into that. At the very least I’m going to show how to put a simple chat system together in Java very soon. I’ve played around with SMSLib for Java and I’ll see if I can find an easy way to explain how to use it. Thank you

      • khan says:

        i want to make an sms message based group messaging service.a boy from our country developed a service and now he is making money..and there are more than 4,000,000 groups ,and 14 million users registerd in there service.his site is this http://www.smsall.pk
        i want to make my very own service like that..i want to flop there service.

        • admin says:

          How much do you know about programming? I’ll revisit the SMS stuff. I was playing with it a few months back.

          • khan says:

            I just know about a little bit python.the creater of smsall.pk .told me that we have created this service using python..i just want to create can we both togethere work on this project?.tell me what do you know about sms stuff like that site.how it works and etc etc

            • admin says:

              I don’t take on projects through this site. Everything I do here is to provide a free education on many subjects. I know it sounds crazy, but I don’t do anything to get rich.

              I will however look into making a Java tutorial on SMS. I have played with it in the past and didn’t have any trouble with it. It is simple to implement, but it is expensive to scale up for hundreds of thousands of potential users.

              I can’t really implement this using Python because of some security issues and the expense that comes along with setting up a Python Django site. I’ll see what I can come up with

              • khan says:

                No want to use my own gsm modem.and sim card.i have already signed a contract with my mobile service provider for free sms..just implement it.and send me the software ready to use ..thank you

  20. Manley says:

    Hello!

    My name is Manley and I have been following your tutorials for sometime now, which by the way have been quite helpful. So thank you :-).
    I have run into a snag with this particular tutorial though.. I am trying to connect to the server(Held on computer A) from another computer(Computer B) on my network through ‘telnet’ ( which I didn’t know anything about lol. Maybe if you are taking suggestions, next time explain a little what that is, or point to a good website to learn about it :) ). Computer B does briefly connect to Computer A but instantly gets an error.. which is the following:

    “chatServer instance has no attribute ‘__trunc__’”

    the full error print is :
    error: uncaptured python exception, closing channel (:[Errno 10022] An invalid argument was supplied [C:\Python27\lib\asyncore.py|read|83] [C:\Python27\lib\asyncore.py|handle_read_event|439] [C:\Users\manley\Desktop\customChat.py|handle_accept|77] [C:\Users\manley\Desktop\customChat.py|__init__|56] [C:\Python27\lib\asyncore.py|listen|337] [C:\Python27\lib\socket.py|meth|224])

    Through the ‘print’ command I have narrowed the error to happen at the ‘self.bind((”, port))’ line.

    Are you able to give me some directions as to what I did wrong? Google is not turning up much for me.. either that or I’m not searching for the right thing :P.

    I am using Windows 7 64bit and Python 2.7

    Thanks!
    Manley

    • admin says:

      Hi Manley, Sorry I didn’t get to you quicker. I was on vacation. Did you replace all of the back quotes with normal quotes in the code?

      You need to replace ‘ and ’ with ‘
      Replace “ and ” with ”

      Did you use the code exactly as I demonstrated and still got the error? I just tested it and it worked.

  21. faiz says:

    are you there ?? please tell me?

  22. Richard says:

    Derek – just finished watching all 18 of your Python tutorials, they were excellent, thank you.

    (ps Khan/faiz whatever your name is. Here’s a radical notion you may not appreciate; try doing a bit of your own research so you can learn how to develop the SMS server yourself, instead of trying to bully others into doing the work 4 u!!!)

  23. Manley says:

    Hey Derek,

    I made a comment about a week ago and its still waiting ‘moderation’. Just wondering if you have had time to read it?

    Manley

  24. verge says:

    Hi, I was trying to get your code working however i am having a couple of issues. At first the script didn’t run so I changed the quotes back to normal quotes. It then opened a connection and i was able to telnet in but none off the messages are being sent to any of the clients. Any ideas?
    Good work on the tutorials btw. Hope to see something with user authentication in the future.

  25. Klayton says:

    “Give me codes for make money and be famous ’cause idk what is computer.”
    Haha! Derek, I applaud you for being polite when I couldn’t. Got a good laugh out of it. :)
    I love your tutorials by the way. They have been very useful! Thanks!

  26. enkidu says:

    Hello there,
    Thank u for nice job.
    Am Computer Security Student And I Chose Secure Messsenger as my Fyp Title.it Filters Incoming Mac Addrssees and only let valid Mac TTo communicate.alsoit Encodes Msgs Befoore send.and It Randomly Downloads immage from Internnet and hide Msg In Image(steganography).may I Have A Look At Your Messengeer source codeplz?did U Finish Authentication Part?andd do U Have Any Suggetioonfor me?u Canemil Me.thank U

  27. Arthur says:

    Hey Derek,

    Really nice tutorial, but I don’t quite understand how to
    get it working. I’m on windows by the way.

    Thanks.

  28. NFiorentini says:

    Welp … I’ve made it through all of your Python 2.X & 3.X videos. I’ve enjoyed and appreciated them.

    I know that you’re a busy guy, but I do hope that you add additional videos to your Python series. Making GUIs, cool desktop apps, a Python-version of the Java Asteroids game perhaps?

    In the interim, do you have any online sources or book recommendations for continuing Python education? In one of the Java tutorials’ comments, you mentioned Filthy Rich Clients and that turned out to be an awesome recommendation.

    Thank you for your tutorials!

    • Derek Banas says:

      You’re very welcome :) I’m glad you enjoyed the Python tutorials. Here are a few books you may like Core Python Applications Programming and Making Games with Python & Pygame. Python is very fun.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Google+