0% found this document useful (0 votes)
6 views2 pages

Server Client Code

Uploaded by

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

Server Client Code

Uploaded by

symoiz2003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Server Code

import socket

# Create a TCP/IP socket


server_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)

# Define server address and port


server_address = ('localhost', 12345)
server_socket.bind(server_address)

# Listen for incoming connections


server_socket.listen(1)
print("Server is listening on port 12345...")

# Wait for a connection


connection, client_address = server_socket.accept()
print(f"Connection established with {client_address}")

try:
while True:
# Receive data in small chunks
data = [Link](1024).decode()
if [Link]() == 'exit':
print("Client requested to close the connection.")
break
print(f"Received from client: {data}")

response = input("Enter response to client: ")


[Link]([Link]())
finally:
[Link]()
print("Server socket closed.")
Client-Side Code
import socket

# Create a TCP/IP socket


client_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server


server_address = ('localhost', 12345)
client_socket.connect(server_address)

try:
while True:
# Send data
message = input("Enter message to send (or type 'exit' to
quit): ")
client_socket.sendall([Link]())

if [Link]() == 'exit':
break

# Receive response
response = client_socket.recv(1024).decode()
print(f"Received from server: {response}")
finally:
client_socket.close()
print("Client socket closed.")

How to Run:

1. Open a terminal and run the server:

python [Link]

2. Open another terminal and run the client:

python [Link]

3. They will exchange messages until either side types "exit".

You might also like