In: Computer Science
Socket Programmimg:
s.socket(): Function implemented in socket module and call to creat socket
s.bind(): This Function bind address Bind(hostname,port) to socket.
s.listen(): This method sets up and start TCP listner
s.accecpt(): This method accecpt TCP client connection waiting until connection is not established.
Thread.start() : start the thread by calling run() method.
/*save file name as server.py*/
import socket
s = socket.socket()
print ("Socket created")
port = 4000
s.bind(('', port))
print ("socket binded with %s" %(port))
# put the socket into listening mode
s.listen(5)
print ("socket start 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 with', addr)
# send a thank you message to the client.
test_string="hello Connection"
res = bytes(test_string, 'utf-8')
c.send( res)
#Close the connection with the client
c.close()
In this code all method is implemented and addr is accecpting connection also to send massege to client i have converted string to bytes to convert bytes i have used bytes(arg,'utf-8') .
Output1 from server side
/*save file name client.py */
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 4000
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# receive data from the server
print(s.recv(1024))
# close the connection
s.close()
OUTput
In this image message received from server side
Also make sure regarding port number in both side is same for communication, here i have set port as 4000
if it is different then there will not be communication between server and client.
Multi Threading Api:
Below i have implemented communication between server and client through threading API
#save file name as server2.py
import socket
# import thread module
from _thread import *
import threading
plock = threading.Lock()
# thread function
def threaded(c):
while True:
# data received from client
d = c.recv(1024)
if not d:
print('Nice To chat')
# lock released on exit
plock.release()
break
# reverse the given string from client
d = d[::-1]
# send back reversed string to client
c.send(d)
# connection closed
c.close()
def Main():
host = ""
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("socket binded with port", port)
# put the socket into listening mode
s.listen(5)
print("socket start listening")
# a forever loop until client wants to exit
while True:
# establish connection with client
c, addr = s.accept()
# lock acquired by client
plock.acquire()
print('Connected to :', addr[0], ':', addr[1])
# Start a new thread and return its identifier
start_new_thread(threaded, (c,))
s.close()
if __name__ == '__main__':
Main()
Output for server side:
The above image is output while client is connected with them if they want to exit then after that a messege is showing like here is Nice to chat.
Client.py
Client side implemented code:
#save file name as client2.py and run
import socket
def Main():
host = '127.0.0.1'
# Define the port on which you want to connect
port = 8000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# connect to server on local computer
s.connect((host,port))
# message you send to server
message = "hello Rajesh"
while True:
# message sent to server
s.send(message.encode('ascii'))
# messaga received from server
d = s.recv(1024)
# print the received message
# here it would be a reverse of sent message
print('message from the server :',str(d.decode('ascii')))
# ask the client whether he wants to continue
ans = input('\n to continue enter(yes/q) :')
if ans == 'yes':
continue
else:
break
# close the connection
s.close()
if __name__ == '__main__':
Main()
The above program is implementaion for client side communication
program communicate while client enter yes if other then that then communication is break
OUTPUT
The above image is output for client side massege received from server is shown in the image and
also it will continue until yes is enter by user (client) otherwise break.