Python Network Socket Programming
Python Network Socket Programming
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first
parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers
to the address family ipv4. The SOCK_STREAM means connection oriented TCP
protocol.
Common Socket Object Methods and Attributes
Name Description
Servers need to “sit on a port” and wait for requests, so they all must bind to a
local address.
Once this setup process is complete, a server can start its infinite loop.
A simple server will then sit on an accept() call, waiting for a connection.
Using the new client socket is similar to handing off a customer call to a service
representative.
When a client eventually does come in, the main switchboard operator takes
the incoming call and patches it through, using another line to connect to the
appropriate person to handle the client’s needs.
This frees up the main line (the original server socket) so that the operator can
resume waiting for new calls (client requests) while the customer and the
service representative he is connected to carry on their own conversation.
In our code, after a client connection is closed, the server goes back to wait for
another client connection. The final line of code, in which we close the server
socket, is optional. It is never encountered because the server is supposed to
run in an infinite loop. We leave this code in our example as a reminder to the
reader that calling the close() method is recommended when implementing an
intelligent exit scheme for the server—for example, when a handler detects
some external condition whereby the server should be shut down.
This script creates a TCP server that accepts messages from clients and returns them with a timestamp
prefix.
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
while True:
print('Waiting for connection...')
tcpCliSock, clntaddr = tcpSerSock.accept()
print('Received Connection and connected to :', clntaddr)
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.close()
tcpSerSock.close()
Line-by-Line Explanation
The HOST variable is blank, which is an indication to the bind() method that it can use any
available address. We also choose a random port number, which does not appear to be used or
reserved by the system. For our application, we set the buffer size to 1K. You can vary this size
based on your networking capability and application needs.
The argument for the listen() method is simply a maximum number of incoming connection
requests to accept before connections are turned away or refused.
The TCP server socket (tcpSerSock) is allocated followed by the calls to bind the socket to the
server’s address and to start the TCP listener.
Once we are inside the server’s infinite loop, we (passively) wait for a connection. When one
comes in, we enter the dialog loop where we wait for the client to send its message. If the
message is blank, that means that the client has quit, so we would break from the dialog loop,
close the client connection, and then go back to wait for another client. If we did get a
message from the client, we format and return the same data but prepend it with the current
timestamp.
The final line is never executed; it is there as a reminder to the reader that a close() call should be
made if a handler is written to allow for a more graceful exit, as we discussed earlier.
--------------------------------------------------------
from socket import *
while True:
data = input('Enter Message to send to server >')
if not data:
break
tcpCliSock.send(bytes(data,"UTF-8"))
data = tcpCliSock.recv(BUFSIZ).decode()
if not data:
break
print(str(data))
tcpCliSock.close()
Lines 3–8
The HOST and PORT variables refer to the server’s hostname and
port number.
Because we are running our test (in this case) on the same
computer, HOST contains the local hostname (change it accordingly
if you are running your server on a different host). The port number
PORT should be exactly the same as what you set for your server
(otherwise, there won’t be much communication). We also choose
the same 1K buffer size.
The TCP client socket (tcpCliSock) is allocated in line 7, followed by
(an active) call to connect to the server.
Now let’s run the server and client programs to see how they work.
Should we run the server first or the client? Naturally, if we ran the client
first, no connection would be possible because there is no server waiting to
accept the request. The server is considered a passive partner because it
has to establish itself first and passively wait for a connection. A client, on
the other hand, is an active partner because it actively initiates a connection.
Server:
A server has a bind() method which binds it to a specific ip and port so that it can listen to
incoming requests on that ip and port.
A server has a listen() method which puts the server into listen mode.
And last a server has an accept() and close() method. The accept method initiates a connection
with the client and the close method closes the connection with the client.
================================================================
import socket
s = socket.socket()
s.bind(('', port))
s.listen(5)
print("socket is listening")
while True:
Passing an empty string means that the server can listen to incoming connections from any
other computers as well.
If we would have passed 127.0.0.1 then it would have listened to only those calls made within
the local computer.
Five here means that 5 connections are kept waiting if the server is busy and if a 6th socket trys
to connect then the connection is refused.
5) At last we make a while loop and start to accept all incoming connections and close those
connections after a thank you message to all connected sockets.
import socket
Then we connect to localhost on port 12345 (the port on which our server runs) and lastly we
receive data from the server and close the connection.
Now save this file as client.py and run it from the terminal after starting the server script.
python client.py