Professional Documents
Culture Documents
Save Now
d e t se e t
Python
This tutorial will give an introduction to sockets in Python and how to use the socket module to
build HTTP servers and clients in Python. It will also cover Tornado, a Python networking library
which is ideal for long polling, WebSockets, and other applications that require a long-lived
connection to each user.
Basically, sockets act as a communication link between two entities, i.e. a server and a client. A
server will give out information being requested by a client. For example, when you visited this
page, the browser created a socket and connected to the server.
1 import socket
2 s= socket.socket (socket_family, socket_type, protocol=0)
After obtaining your socket object, you can then create a server or client as desired using the
methods available in the socket module.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
To create a new socket, you rst import the socket method of the socket class.
1 import socket
The AF_INET argument indicates that you're requesting an Internet Protocol (IP) socket,
speci cally IPv4. The second argument is the transport protocol type SOCK_STREAM for TCP
sockets. Additionally, you can also create an IPv6 socket by specifying the socket AF_INET6
argument.
1 server = "localhost"
1 port =80
It's important to note that the host and port must be a tuple.
1 message = 'message'
2 stream_socket.sendall(message)
1 data = sock.recv(10)
2 print data
1 stream_socket.close()
01 import socket
02 import sys
03
04 # Create a TCP/IP socket
05 stream_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
06
07 # Define host
08 host = 'localhost'
09
10 # define the communication port
11 port = 8080
12
13 # Connect the socket to the port where the server is listening
14 server_address = ((host, port))
15
16 print "connecting"
17
18 stream_socket.connect(server_address)
19
20
21 # Send data
22 message = 'message'
23 stream_socket.sendall(message)
24
25 # response
26 data = stream_socket.recv(10)
27 print data
28
29
30 print 'socket closed'
31 stream_socket.close()
Build a Simple Server
Now let's take a look at a simple Python server. The following are the socket server methods
available in Python.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Create a socket.
Bind the socket to a port.
Start accepting connections on the socket.
01 import socket
02 import sys
03
04 # Create a TCP/IP socket
05 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
06
07 # Define host
08 host = 'localhost'
09
10 # define the communication port
11 port = 8080
12
13 # Bind the socket to the port
14 sock.bind((host, port))
15 # Listen for incoming connections
16 sock.listen(1)
17
18 # Wait for a connection
19 print 'waiting for a connection'
20 connection, client = sock.accept()
21
22 print client, 'connected'
23
24 # Receive the data in small chunks and retransmit it
25
26 data = connection.recv(16)
27 print 'received "%s"' % data
28 if data:
29
30 connection.sendall(data)
31 else:
32 print 'no data from', client
33
34
35 # Close the connection
36 connection.close()
Now run the client and server programs in separate terminal windows, so they can communicate
with each other.
Server Output
1 $ python server.py
2 waiting for a connection
3 ('127.0.0.1', 47050) connected
4 received "message"
Client Output
1 $ python client.py
2 connecting
3 message
4 socket closed
Tornado is a Python web framework and asynchronous networking library. Tornado uses the non-
blocking network I/O, and hence is capable of scaling to tens of thousands of open connections.
This trait makes it ideal for long polling, WebSockets, and other applications that require a long-
lived connection to each user.
01 import tornado.ioloop
02 import tornado.web
03
04
05 class ApplicationHandler(tornado.web.RequestHandler):
06
07 def get(self):
08 self.message = message = """<html>
09 <head>
10 <title>Tornado Framework</title>
11
12 </head>
13 <body
14 <h2>Welcome to the Tornado framework</h2>
15 </body>
16 </html>"""
17 self.write(message)
18
19
20 if __name__ == "__main__":
21 application = tornado.web.Application([
22 (r"/", ApplicationHandler),
23 ])
24 application.listen(5001)
25 tornado.ioloop.IOLoop.instance().start()
We de ne the class ApplicationHandler which serves as the handler for a request and
returns a response using the write() method.
The main method is the entry for the program.
tornado.web.Application creates a base for the web application and takes a collection of
handlers, i.e. ApplicationHandler.
The Application listens on port 5000, and a client can communicate to this application using
the same port.
tornado.ioloop.IOLoop.instance().start() creates a nonblocking thread for an application.
If we run the application, we will get the result as shown in the screenshot below.
Conclusion
By now you must have grasped the basics of socket programming in Python and how you can
build a simple server and client. Feel free to experiment by building your own chat client. For
more information, visit the o cial Python docs.
Additionally, don’t hesitate to see what we have available for sale and for study in the Envato
Market, and don't hesitate to ask any questions and provide your valuable feedback using the
feed below.
Advertisement
Esther Vaati
Software developer
Esther is a software developer based in Kenya. She is very passionate about technology.
She is also a programming instructor at Envato Tuts+. When she is not coding, she loves to
watch movies and do volunteer work.
Kaleiesther
Email Address
Update me weekly
Advertisement
Translations
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Powered by
LOG IN WITH
OR SIGN UP WITH DISQUS ?
Name
✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy
Advertisement
ENVATO TUTS+
HELP
© 2019 Envato Pty Ltd. Trademarks and brands are the property of their respective owners.