Socket Programming-Python
Hey hi everyone so today we will learn how the base of internet i.e. the sockets works,and how the client socket and the server socket function over the internet.
Before going to the coding part let me give you a basic idea on how the clients and the server talks,or how do they interact.
Firstly when the client connects to the server and requests the server for some information,the server then responds with some answer,maybe it will respond by showing you a page you asked for or by responding like ‘page not found’.
Basic idea about the program:
Language : Python
Number of files: 2 ,server.py and client.py
Now lets begin with the programming part,
Lets create our server first.
server.py
#we need the socket library first,we will import it by,import sockets = socket.socket()#the 's' is a variable used to describe the server socket
# in bracket we need to mention the type of ip and the type of network,like ipv4/ipv6 and for network is it TCP or UDP connection,by default it will use ipv4 and TCP connectionprint('Socket Created')
s.bind(('localhost',9999))#here in bracket we will put the IP address and the port number,here I have given 'localhost' as for using it in the same machine,but if you want to try by using 2 or more computers,then change the localhost to the IP address of the computer you want to use as a server.(To check the IP address,for windows machine use: ipconfig in cmd and for linux machine use:ifconfig in a terminal.
s.listen(3)#here in bracket we will have to mention the number of connection my server will work at once,for here my server will work with only 3 connections for more connections just change the number inside the brackets.print('Waiting for connections')
while True:
c,addr = s.accept()# here c means the client socket, so in this case out server socket is accepting the client socket and the address also
name=c.recv(1024).decode()
print("Connected Successfully with",addr,name)
c.send(bytes('Welcomw to My World','utf-8'))
c.close()
# and always close the connection.
client.py
#we need the socket library first,we will import it by,import socket
c = socket.socket()#the 'c' is a variable used to describe the server socket
# in bracket we need to mention the type of ip and the type of network,like ipv4/ipv6 and for network is it TCP or UDP connection,by default it will use ipv4 and TCP connectionc.connect(('localhost',9999))#here in bracket we will put the IP address and the port number,here I have given 'localhost' as for using it in the same machine,but if you want to try by using 2 or more computers,then change the localhost to the IP address of the computer you want to use as a server.(To check the IP address,for windows machine use: ipconfig in cmd and for linux machine use:ifconfig in a terminal.name = input("Enter Your Name")
c.send(bytes(name,'utf-8'))
print(c.recv(1024).decode())#here i used .decode as i need the output in string format.
Screenshots
Cheers!❤
-VirusZzWarning