TCP_Socket_prog
TCP_Socket_prog
Socket
Programming
1
Client-Server Model
Every network application is based on client-server model:
A Server process (program) and one or more client
processes.
Server manages some resources or provides some service
by using resources to clients.
192.18.22.1
Using Ports to Identify Services
Server host 134.173.42.2
Service request
for Web
134.173.42.2:2 server
5 Kerne (port 80)
Client
(i.e., E-mail l E-Mail
server) server
(port 25)
Socket
What is a Socket?
It is a protocolsindependent interface to multiple
transport
layer services.
To kernel, socket is endpoint of communication.
To application, socket is file descriptor that lets
application
read from or write to network.
It is an interface (a “door”) into which an application
process can send and receive messages to/from
another (remote or local) application process.
Clients and servers communicate with each other by
sending to
and receiving from socket descriptors.
Every endpoint (socket) is identified by Address
and Port
Socket
Interface
It is the interface between application and protocol
software.
8
Internet Connections
Clients and servers communicate by sending streams of
bytes over connections.
Connections are point-to-point, full-duplex (2-way
communication), and reliable.
Send/Receive data
Shutdown connection
Server (TCP) – high level
view Create a socket
Send/Receive data
Shutdown connection
TCP Client-Server interaction using Sockets API
import socket
s = socket.socket (family, type, proto)(returns Socket descriptor)
family specifies address or protocol family. Can be AF_INET
(default)
AF_INET6, etc.
type specifies socket type. Can be SOCK_STREAM (default)(TCP)
SOCK_DGRAM (UDP) etc.
proto (protocol) argument is normally left to zero.
sock.connect((‘192.168.10.52’,12000)) 1
7
Function for sending
data
import socket
socket.send(bytes)
sock.send("this is nizam".encode())
or
sock.send(b‘this is nizam’)
1
8
Function for receiving
data
import socket
socket.recv(bufsize)
Receive data from the socket.
The maximum amount of data to be received at
once is
specified by bufsize.
The return value is a bytes object representing the
data received.
Note: For best match with hardware and network realities, the value
of
bufsize should be a relatively small power of 2, for example,
1024,2046 etc. =sock.recv(2046)
M (bytes)
or
M (string) =sock.recv(2046).decode()
1
9
Closing a
import socket socket
socket.close()
Mark the socket closed.
The transport layer generally tries to flush out, i.e.
send, any
remaining data, when a close is done.
The underlying system resource is closed. Once that
happens, all future operations on the socket object will
fail. The remote end will receive no more data.
sock.close()
2
0
TCP Server side Socket functions
Associating a local address with a
socket
Import socket
socket.bind(address)
Bind the socket to address. The socket must not
already be bound.