0% found this document useful (0 votes)
10 views

TCP socket

Uploaded by

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

TCP socket

Uploaded by

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

Page 1

TCP socket
What is a socket
It’s software needed to connect two components or computers
to form a communication links
Protocols
Communication protocols specify the rules of how and in
what format information should be sent and received.
These protocols are assembled into a hierarchy to
manage the various tasks involved in network
communication.
In other words, some protocols handle how hardware
receives, sends, or routes packets, while others are more
high-level and are concerned, for example, with
application-level communication etc.
Some commonly used and widely well-known network
communication protocols include:
Page 2

1- WI-FI
2- BLUETOOTH

3- IP (Internet Protocol)
IP is a network layer protocol mainly responsible for
routing packets and IP addressing.

4- TCP (Transmission Control


Protocol)
A reliable, connection-oriented protocol that provides full
duplex communication and ensures data integrity and
delivery. This is a transport layer protocol, which manages
connections, detects errors, and controls information flow.
5-UDP (User Datagram Protocol)
A protocol from the same protocol suite as TCP. The main
difference is that UDP is a more simple, fast, but
unreliable connectionless protocol that does not perform
any delivery checks and follows the paradigm of “fire-and-
forget.” As TCP, UPD is also located on the transport
layer.
3- HTTP (Hypertext Transfer Protocol)
An application layer protocol and the most commonly used
protocol for browser-to-server communication on the web,
used to serve websites in particular. It goes without saying
that this article that you are reading right now was also
Page 3

served via HTTP. HTTP protocol builds on top of TCP and


manages and transfers information relevant to web
applications like headers, which are used to transfer
metadata and cookies, different HTTP methods (GET,
POST, DELETE, UPDATE) etc.
4- MQTT (Message Queue Telemetry Transport)
Another example of an application-level protocol used for
devices with limited processing power and battery life,
operating in unreliable network conditions (for example,
gas sensors on a mining site or simply a smart light bulb in
your house). MQTT is a standard messaging protocol
used in IoT (Internet of Things). It is both lightweight and
simple to use, designed with built-in retransmission
mechanisms for enhanced reliability. If you're interested in
using this protocol with Python, you can read this Python
MQTT guide that provides an in-depth overview of the
Paho MQTT client.
An important observation is that all the above mentioned
protocols use sockets under the hood ,but add their own
logic and data processing on top. This is due to sockets
being a low-level interface for any network
communications in modern devices as we will discuss in
the next section.
Page 4

TCP socket python have one socket class for all, the
difference is in methods and protocols

Create TCP Client Socket In Python Steps.


1. Import the python socket module, this is a built-in module.
import socket
Page 5

2. Call the socket.socket(socket.AF_INET, socket.SOCK_STREAM) function to


create the client socket, please note the function parameters.
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

3. Connect to the server socket by invoking the above client socket


object’s client_socket.connect((‘localhost’, 8999)) function.
The connect() function’s input parameter is a tuple object that contains the
server socket machine hostname/IP and port number.
client_socket.connect(('localhost', 8999))

4. Call the client socket object’s send () or sendall() function to send text data
to the server socket. The function’s input parameter is a bytes object, so you
need to encode the send text before sending it.
client_socket.sendall(user_input_str.encode('utf-8'))

5. Call the client socket object’s client_socket.recv(1024) function to read the


text that the server socket sends back.
data_tmp = client_socket.recv(1024)

6. The received data is also a bytes object, you need to convert it to a text string
by invoking the bytes object’s function decode(‘utf-8’).
str_tmp = data_tmp.decode('utf-8')

7. Call the client socket’s close() function to close the socket connection.
client_socket.close()

1.2 Create TCP Server Socket In Python Steps.

1. Import the python socket module.


import socket

2. Create the server socket object by invoking the


function socket.socket(socket.AF_INET, socket.SOCK_STREAM).
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

3. Bind the socket object to a host and a port number with the socket
object’s bind( server_info_tuple_object ) function.
4. server_socket.bind(('localhost', 8080))

5. Make the socket object be a server socket by invoking


it’s listen(maximize_queue_size) function.
Page 6

The maximize_queue_size parameter is the number of the maximize socket


connections that are waiting for the server socket to accept in the queue.
server_socket.listen(1)

6. Call the server socket object’s accept() function to accept the client socket
request, it will return a connection object and the client socket IP address.
(connection, client_ip) = server_socket.accept()

7. Call the connection object’s recv(buffer_size) function to read the data sends
from the client socket.
data = connection.recv(1024)

8. The readout data is also a bytes type object, you need to invoke
it’s decode(‘utf-8’) function to convert it to a string.
data_str = data.decode('utf-8')

9. Call the connection object’s send(data) or sendall(data) function to send


data back to the client socket.
connection.sendall('hello client, just received your data.'.encode('utf-
8'))

10. Call the connection object’s close() function to close the socket connection.
connection.close()
Page 7

#server side socket


import socket

HOST = "127.0 .0.1" # Standard loopback interface address (localhost)


PORT = 65432 # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:


s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
Page 8

# Client Socket

import socket

HOST = "127.0.0.1" # The server's hostname or IP address


PORT = 65432 # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:


s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)

print(f"Received {data!r}")

Constants

The AF_* and SOCK_* constants are now AddressFamily and SocketKind IntEnum collections.

New in version 3.4.

socket.AF_UNIX
socket.AF_INET
socket.AF_INET6

These constants represent the address (and protocol) families, used for the first argument
to socket(). If the AF_UNIX constant is not defined then this protocol is unsupported. More
constants may be available depending on the system.
socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET
These constants represent the socket types, used for the second argument to socket(). More
constants may be available depending on the system.
(Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.)
socket.SOCK_CLOEXEC
socket.SOCK_NONBLOCK
Page 9

These two constants, if defined, can be combined with the socket types and allow you to set
some flags atomically (thus avoiding possible race conditions and the need for separate calls).

You might also like