Question

In: Computer Science

write a skeleton Python TCP servers as follows: Multi-threaded concurrent TCP server using Python’s low-level socket...

write a skeleton Python TCP servers as follows:

Multi-threaded concurrent TCP server using Python’s low-level socket module and Python’s threading library

Python sockets API:
s = socket(), s.bind(), s.listen(), remote_socket,
remote_addr = s.accept()

Python threading API:
thread = threading.Thread(target, args, daemon), thread.start()

Solutions

Expert Solution

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.


Related Solutions

Write a Java program that establishes a TCP connection with a mail server through the socket...
Write a Java program that establishes a TCP connection with a mail server through the socket interface, and sends an email message. Your program sends SMTP commands to local mail server, receives and processes SMTP commands from local mail server. It sends email message to one recipient at a time. The email message contains a typical message header and a message body. Here is a skeleton of the code you'll need to write: import java.io.*; import java.net.*; public class EmailSender...
How to create a FTP server using python and TCP Ports How to create a FTP...
How to create a FTP server using python and TCP Ports How to create a FTP server using python and UDP Ports
How do I make a simple TCP python web client and web server using only "import...
How do I make a simple TCP python web client and web server using only "import socket"? Basically, the client connects to the server, and sends a HTTP GET request for a specific file (like a text file, HTML page, jpeg, png etc), the server checks for the file and sends a copy of the data to the client along with the response headers (like 404 if not found, or 200 if okay etc). The process would be: You first...
Using C as the programming language, Write a concurrent connection-oriented server that can do something simple...
Using C as the programming language, Write a concurrent connection-oriented server that can do something simple for connected clients. It should be able to carry out such processing for the client as many times as the client wants until the client indicates it wishes to end the session. The server should support multiple clients (use telnet as the client in this task). Compile and run the server program. Try and connect to it from multiple other hosts using telnet as...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT