0% found this document useful (0 votes)
9 views5 pages

ex_4

The document discusses socket programming and the client-server model, explaining the roles of servers and clients in network communication. It details the types of sockets (TCP and UDP) and provides example code for a simple server and client using the Twisted framework in Python. The implementation demonstrates how to establish connections, send and receive messages, and handle client-server interactions.

Uploaded by

medha8988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

ex_4

The document discusses socket programming and the client-server model, explaining the roles of servers and clients in network communication. It details the types of sockets (TCP and UDP) and provides example code for a simple server and client using the Twisted framework in Python. The implementation demonstrates how to establish connections, send and receive messages, and handle client-server interactions.

Uploaded by

medha8988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Ex No.

: 4

Study of Socket Programming and Client-Server Model

Socket Programming enables communicaton between processes across a network or


between processes on the same computer .It’s based on the client-server model where one
program acts as a server waiting for incoming requests and another program acts as a client
making requests to the server.

Client-Server Model:
1. Server:

 The server is a program that provides services or


resources to other programs or devices, known as clients.

 It waits for incoming connections from clients and handles their requests.
• Once a connection is established, the server processes client

requests and sends back responses.


2. Client:

 The client is a program or device that requests services or

resources from the server.

 It initiates a connection to the server, sends requests for

services, and receives responses.

 Clients can connect to multiple servers to utilize different services.

Server/Active Port: (ping_server.py)


Socket Programming:
1. Socket:

 A socket is a communication endpoint that allows two processes to


communicate with each other.
 It's identified by an IP address and a port number.
 Sockets can be of different types like Stream Sockets (TCP) or Datagram
Sockets (UDP).
2. ТСР (Тransmission Control Protocol):

 TCP provides reliable, ordered, and error-checked


delivery of data between applications.
 It establishes a connection-oriented communication channel
between the client and server.

 Communication is done using streams of data, ensuring data

integrity and order.


3. UDP (User Datagram Protocol):
 UDP provides an unreliable and connectionless communication service.
 It's faster and more lightweight compared to TCP but doesn't guarantee
delivery or ordering of data.
 Communication is done by sending individual packets called datagrams.

Code:
Socket Server Model Code(server.py)

from twisted.internet import reactor, protocol

class SimpleServer(protocol.Protocol):

def connectionMade(self):

"""Called when a client connects."""


self.client_ip = self.transport.getPeer().host

print(f"[INFO] Client {self.client_ip} connected.")

self.transport.write(b"Welcome to the Twisted Server!\n")

def dataReceived(self, data):

"""Handles incoming data from the client."""

message = data.decode().strip()

print(f"[RECEIVED] From {self.client_ip}: {message}")


response = f"[SERVER] Received: {message}\n"

self.transport.write(response.encode())
def connectionLost(self, reason):

"""Called when a client disconnects."""


print(f"[INFO] Client {self.client_ip} disconnected.")

class SimpleFacory(protocol.Factory):

def buildProtocol(self, addr):

"""Creates a new instance for each connection."""


return SimpleServer()
if __name__ == "__main__":

port = 8888

reactor.listenTCP(port, SimpleFactory()) # Listen on port 8888

print(f"[INFO] TCP Server is running on port {port}...")

reactor.run()

Socket Client Model Code(client.py)

from twisted.internet import reactor, protocol


import threading

class SimpleClient(protocol.Protocol):
def connectionMade(self):

"""Called when connection is established."""


print("[INFO] Connected to server.")

threading.Thread(target=self.send_data, daemon=True).start() # Start input loo

def dataReceived(self, data):


"""Handles messages received from the server."""

print(f"[SERVER] {data.decode().strip()}")

def send_data(self):

"""Sends messages to the server continuously."""


while True:
msg = input("Enter message to send (type 'exit' to quit): ")

if msg.lower() == 'exit':
print("[INFO] Closing connection...")

reactor.stop()
break

self.transport.write(msg.encode())

class SimpleClientFactory(protocol.ClientFactory):

def buildProtocol(self, addr):


print("[INFO] Connecting to server...")
return SimpleClient()

def clientConnectionFailed(self, connector, reason):

print(f"[ERROR] Connection failed: {reason}")

reactor.stop()

def clientConnectionLost(self, connector, reason):


print("[INFO] Connection closed by server.")
reactor.stop(

# Connect to the server on localhost and port 8888


reactor.connectTCP("127.0.0.1", 8888, SimpleClientFactory())

reactor.run()
Output:

On client side:

On server side:

RESULT:

Thus the Client Server Architecture is implemented in twisted python and a report for the
model architecture is prepared.

You might also like