Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
204 views

Python Network Socket Programming

A socket is an endpoint in a communication between programs over a network. It is bound to a port number so the TCP layer knows which application to send data to. A socket is created using the socket.socket() function, specifying the address family and socket type. A TCP server creates a socket, binds it to an address and port, listens for connections, and accepts connections from clients to communicate through a new socket before listening again.

Uploaded by

vsnpradeep
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
204 views

Python Network Socket Programming

A socket is an endpoint in a communication between programs over a network. It is bound to a port number so the TCP layer knows which application to send data to. A socket is created using the socket.socket() function, specifying the address family and socket type. A TCP server creates a socket, binds it to an address and port, listens for connections, and accepts connections from clients to communicate through a new socket before listening again.

Uploaded by

vsnpradeep
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 10

Definition: 

A socket is one endpoint of a two-way communication link between two


programs running on the network. A socket is bound to a port number so that
the TCP layer can identify the application that data is destined to be sent to.

An endpoint is a combination of an IP address and a port number. Every TCP


connection can be uniquely identified by its two endpoints. That way you can
have multiple connections between your host and the server

Socket Module in Python


To create a socket, we must use socket.socket() function available in the
Python socket module, which has the general syntax as follows:
S = socket.socket(socket_family, socket_type, protocol=0)
 socket_family: This is either AF_UNIX or AF_INET. We are only going to
talk about INET sockets, as they account for at least 99% of the sockets
in use.
 socket_type: This is either SOCK_STREAM or SOCK_DGRAM.

 Protocol: This is usually left out, defaulting to 0.

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

Server Socket Methods

Name Description

s.bind() Bind address (hostname, port number pair) to socket

s.listen() Set up and start TCP listener

s.accept() Passively accept TCP client connection, waiting until


connection arrives (blocking)

Client Socket Methods

s.connect() Actively initiate TCP server connection

s.connect_ex() Extended version of connect(), where problems


returned as error codes rather than an exception
being thrown

General Socket Methods

s.recv() Receive TCP message

s.recv_into() Receive TCP message into specified buffer

s.send() Transmit TCP message

s.sendall() Transmit TCP message completely

s.getpeername() Remote address connected to socket (TCP)

s.getsockname() Address of current socket

s.shutdown() Shut down the connection

s.close() Close socket


Creating a TCP Server

ss = socket() # create server socket

ss.bind() # bind socket to address

ss.listen() # listen for connections

inf_loop: # server infinite loop

cs = ss.accept() # accept client connection

comm_loop: # communication loop

cs.recv()/cs.send() # dialog (receive/send)

cs.close() # close client socket

ss.close() # close server socket # (opt)

All sockets are created by using the socket.socket() function.

Servers need to “sit on a port” and wait for requests, so they all must bind to a
local address.

Because TCP is a connection-oriented communication system, some


infrastructure must be set up before a TCP server can begin operation.

In particular, TCP servers must “listen” for (incoming) connections.

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.

Once a connection is accepted, a separate client socket is returned (by accept())


for the upcoming message interchange.

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.

Likewise, when an incoming request arrives, a new communication port is


created to converse directly with that client, again, leaving the main port free to
accept new client connections.

Once the temporary socket is created, communication can commence, and


both client and server proceed to engage in a dialog of sending and receiving,
using this new socket until the connection is terminated. This usually happens
when one of the parties either closes its connection or sends an empty string to
its counterpart.

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.

TCP Server (tsTserv.py)

This script creates a TCP server that accepts messages from clients and returns them with a timestamp
prefix.

from socket import *


from time import ctime

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)


tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

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

sdata = '[%s] %s' % (ctime(),data)


tcpCliSock.send(sdata.encode())

tcpCliSock.close()
tcpSerSock.close()

Line-by-Line Explanation

We import time.ctime() and all the attributes


from the socket module.

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 *

HOST = '127.0.0.1' # or 'localhost'


PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)


tcpCliSock.connect(ADDR)

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()

Line By Line Explanation

we import all the attributes from the socket module.

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.

Executing Our TCP Server and Client(s)

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.

A simple server-client program :

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.

This allows the server to listen to incoming connections.

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.

================================================================

# first of all import the socket library

import socket

# next create a socket object

s = socket.socket()

print("Socket successfully created")

# Reserve a port on your computer


# In our case it is 12345 but it can be anything > 1024 and <= 65535
port = 12345

# Next bind to the port


# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network

s.bind(('', port))

print("socket binded to",port)

# put the socket into listening mode

s.listen(5)

print("socket is listening")

# a forever loop until we interrupt it or an error occurs

while True:

# Establish connection with client.


c, addr = s.accept()
print('Got connection from', addr)

# send a thank you message to the client.


c.send('Thank you for connecting')

# Close the connection with the client


c.close()

1) First we need to import the socket module which is necessary.

2) Then we need to create a socket object

3) After that we binded our server socket to a specified port.

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.

4) After that we put the server into listen mode.

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.

Now for the client side:

# Import socket module

import socket

# Create a socket object


s = socket.socket()

# Define the port on which you want to connect


port = 12345

# connect to the server on local computer


s.connect(('127.0.0.1', port))

# receive data from the server


print(s.recv(1024))
# close the connection
s.close()

First of all we make a socket object.

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.

start the server:


python server.py

Socket successfully created


socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 52617)

# start the client:

python client.py

Thank you for connecting

You might also like