[Link]@yahoo.
com Naresh i Technologies
Socket Programming
Socket Programming:
Socket programming is a way of connecting two computers on a network to
communicate with each other.
Network:
A set of co operative interconnected computers is called as network.
Sockets make the transfer of information possible between two different
programs or devices.
Client Socket:
A client socket is a connection end at client side.
Server Socket:
A server socket is a connection end at server side.
Port Number:
It is used to identify the service over network or internet. Port numbers range is 0
to 65535.
Reserved port numbers range is 0 to 1023 whereas free port numbers range is
1024 to 65535.
To achieve socket programming in python, we need the following
methods of socket module.
1) socket() => Used to create sockets at both client side and server side.
2) accept() => Used to accept the connection. It returns socket object and
address.
3) bind() => Used to bind the address and port number.
4) close() => Used to close the socket.
5) listen() => Used to enable the server to listen connections.
6) gethostname() => Used to get the host name.
Python By Venkatesh Mansani Naresh i Technologies
[Link]@[Link] Naresh i Technologies
7) send() => Used to send the information.
8) recv() => Used to receive the information.
9) connect() => Used to establish a connection.
Examples:
1) Program to get the ip address of the system:
import socket
ip=[Link]("[Link]")
print(ip)
2) Program to send the request to convert the given string into
capital letters to server:
Server Program:
from socket import *
s=socket()
[Link](("localhost",2000))
[Link](1)
c,add=[Link]()
msg1=[Link](1000)
msg2=[Link]("utf-8")
msg3=[Link]()
msg4=[Link]("utf-8")
[Link](msg4)
[Link]()
Client Program:
from socket import *
s=socket()
[Link](("localhost", 2000))
msg1=input("Enter any message in lower case letters: ")
msg2=[Link]("utf-8")
Python By Venkatesh Mansani Naresh i Technologies
[Link]@[Link] Naresh i Technologies
[Link](msg2)
msg3=[Link](1000)
msg4=[Link]("utf-8")
print("From Server: ", msg4)
[Link]()
3) Program to demonstrate chatting program:
Server Program:
from socket import *
s=socket()
[Link](("localhost",2000))
[Link](1)
c,add=[Link]()
while True:
msg1=[Link](1000)
msg2=[Link]("utf-8")
print(“From Client: “, msg2)
msg3=input(“To Client: “)
msg4=[Link](“utf-8”)
[Link](msg4)
Client Program:
from socket import *
s=socket()
[Link](("localhost", 2000))
while True:
msg1=input("To Server: ")
msg2=[Link]("utf-8")
[Link](msg2)
msg3=[Link](1000)
msg4=[Link]("utf-8")
print("From Server: ", msg4)
Python By Venkatesh Mansani Naresh i Technologies