You are on page 1of 7

1.

Connection establishment from server to client:

Server-side:

# 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
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 %s" %(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. encoding to send byte type.
c.send('Thank you for connecting'.encode())
# Close the connection with the client
c.close()
# Breaking once connection closed
break

Client-side:
# Import socket module
import socket
# Create a socket object
c = socket.socket()
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
c.connect(('127.0.0.1', port))
# receive data from the server and decoding to get the string.
print (c.recv(1024).decode())
# close the connection
c.close()

2. Connecting Google server:

# An example script to connect to Google using socket


# programming in Python
import socket # for socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
except socket.error as err:
print ("socket creation failed with error %s" %(err))
# default port for socket
port = 80
try:
host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:
# this means could not resolve the host
print ("there was an error resolving the host")
sys.exit()
# connecting to the server
s.connect((host_ip, port))
print ("the socket has successfully connected to google")

3. Chatting between server and client


Server side
import socket
host = socket.gethostname()
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ('Got connection from'+str(addr))
while True:
data=conn.recv(1024).decode()
if not data:
break
print("from connected user:"+str(data))
data = input('->')
conn.send(data.encode())
conn.close()
Client side:
import socket
host = socket.gethostname()
port = 5000
c = socket.socket()
c.connect((host, port))
message = input('->')
while message.lower().strip()!='bye':
c.send(message.encode())
data=c.recv(1024).decode()
print("received from server:"+ data)
message = input('->')
c.close()

4. UDP Socket Programming:

Server side:

import socket
localIP = "127.0.0.1"
localPort = 20001
bufferSize = 1024
UDPServerSocket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")
# this might be database or a file
di ={'17BIT0382':'vivek', '17BEC0647':'shikhar', '17BEC0150':'tanveer','17BCE2119':'sahil',
'17BIT0123':'sidhant'}

while(True):
# receiving name from client
name, addr1 = UDPServerSocket.recvfrom(bufferSize)
# receiving pwd from client
pwd, addr1 = UDPServerSocket.recvfrom(bufferSize)
name = name.decode()
pwd = pwd.decode()
msg =''
if name not in di:
msg ='name does not exists'
flag = 0
for i in di:
if i == name:
if di[i]== pwd:
msg ="pwd match"
flag = 1
else:
msg ="pwd wrong"
bytesToSend = str.encode(msg)
# sending encoded status of name and pwd
UDPServerSocket.sendto(bytesToSend, addr1)

Client side:
import socket
# user input
name = input('enter your username : ')
bytesToSend1 = str.encode(name)
password = input('enter your password : ')
bytesToSend2 = str.encode(password)
serverAddrPort = ("127.0.0.1", 20001)
bufferSize = 1024
# connecting to hosts
UDPClientSocket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM)
# sending username by encoding it
UDPClientSocket.sendto(bytesToSend1, serverAddrPort)
# sending password by encoding it
UDPClientSocket.sendto(bytesToSend2, serverAddrPort)
# receiving status from server
msgFromServer = UDPClientSocket.recvfrom(bufferSize)
msg = "Message from Server {}".format(msgFromServer[0].decode())
print(msg)
5. File transfer through TCP

Server side:

import socket
IP = socket.gethostbyname(socket.gethostname())
PORT = 4455
ADDR = (IP, PORT)
SIZE = 1024
FORMAT = "utf-8"
print("[STARTING] Server is starting.")
""" Staring a TCP socket. """
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
""" Bind the IP and PORT to the server. """
server.bind(ADDR)
""" Server is listening, i.e., server is now waiting for the client to connected. """
server.listen()
print("[LISTENING] Server is listening.")
while True:
""" Server has accepted the connection from the client. """
conn, addr = server.accept()
print(f"[NEW CONNECTION] {addr} connected.")

""" Receiving the filename from the client. """


filename = conn.recv(SIZE).decode(FORMAT)
print(f"[RECV] Receiving the filename.")
file = open(filename, "w")
conn.send("Filename received.".encode(FORMAT))

""" Receiving the file data from the client. """


data = conn.recv(SIZE).decode(FORMAT)
print(f"[RECV] Receiving the file data.")
print(data)
file.write(data)
conn.send("File data received".encode(FORMAT))

""" Closing the file. """


file.close()

""" Closing the connection from the client. """


conn.close()
print(f"[DISCONNECTED] {addr} disconnected.")

Client side:
import socket

IP = socket.gethostbyname(socket.gethostname())
PORT = 4455
ADDR = (IP, PORT)
FORMAT = "utf-8"
SIZE = 1024

""" Staring a TCP socket. """


client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
""" Connecting to the server. """
client.connect(ADDR)

""" Opening and reading the file data. """


file = open("yt.txt", "r")
data = file.read()

""" Sending the filename to the server. """


client.send("yt.txt".encode(FORMAT))
msg = client.recv(SIZE).decode(FORMAT)
print(f"[SERVER]: {msg}")

""" Sending the file data to the server. """


client.send(data.encode(FORMAT))
msg = client.recv(SIZE).decode(FORMAT)
print(f"[SERVER]: {msg}")

""" Closing the file. """


file.close()

""" Closing the connection from the server. """


client.close()

File to be transferred
yt.txt
hi
hello

You might also like