Professional Documents
Culture Documents
Server-side:
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()
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.")
Client side:
import socket
IP = socket.gethostbyname(socket.gethostname())
PORT = 4455
ADDR = (IP, PORT)
FORMAT = "utf-8"
SIZE = 1024
File to be transferred
yt.txt
hi
hello