Creating a Simple Chat Application with Python

Creating application with Python is very simple, here is a simple chat application made by using the socket module, it has 2 parts First Server and Second client, you run the server first and then connect the client to it, here is the code

Here is the Server Code

#!/usr/bin/env python

from socket import *
from time import time, ctime

IP = ''
PORT = 23456
ADS = (IP, PORT)

tcpsoc = socket(AF_INET, SOCK_STREAM)
tcpsoc.bind(ADS)
tcpsoc.listen(5)

while 1:
print "Waiting for connection"
tcpcli, addr = tcpsoc.accept()
print "connected from:", addr
while 1:
data = tcpcli.recv(1024)
if not data : break
print data
data1 = raw_input(">>")
if data1 == "q;t": break
tcpcli.send(data1)
tcpcli.close()
tcpsoc.close()

Here is the client code

#!/usr/bin/env python

from socket import *

IP = ''
PORT = 23456
ADS = (IP, PORT)

tcpsoc = socket(AF_INET, SOCK_STREAM)
tcpsoc.connect(ADS)

while 1:
data = raw_input("msg>>")
if not data : break
tcpsoc.send(data)
data = tcpsoc.recv(1024)
if not data: break
print data
tcpsoc.close()

the code above might not be properly intended so you can download the code from http://fb.ankurs.com/tcp_server.py and http://fb.ankurs.com/tcp_client.py
enjoy!!!

Tags: , , , , ,

This entry was posted on Thursday, May 1st, 2008 at 8:27 am and is filed under Life, Linux, Special. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “Creating a Simple Chat Application with Python”

Jonathan Biddle February 28th, 2009 at 12:41 am

Thanks! I was looking for a simple chat setup to play with, and this fit the bill.

Also, for code embeds check out snipt: http://snipt.net . They make it super easy to include syntax-highlighted code in blogs.

James February 6th, 2010 at 3:25 am

Any license on your code here? It’s one of the things that can’t be written too many ways, but it’s something I’d like to play with and possibly distribute.

Ankur Shrivastava March 12th, 2010 at 12:14 am

@James
the code above can be used as you wish without any particular licence but code else were is under GPLv3 unless mentioned otherwise…

Leave a Reply