Question

In: Computer Science

Write a Python Client/Server Socket Program that will allow you to send text messages between the...

Write a Python Client/Server Socket Program that will allow you to send text messages between the server and client, terminating when the exit is typed on the client. Build the program on your 2-VM’s and get it working. Cut and paste your code below along with screen shots of your program working.

Solutions

Expert Solution

So, what is a server? Well, a server is a software that waits for client requests and serves or processes them accordingly.

On the other hand, a client is requester of this service. A client program request for some resources to the server and server responds to that request.

Socket is the endpoint of a bidirectional communications channel between server and client. Sockets may communicate within a process, between processes on the same machine, or between processes on different machines. For any communication with a remote program, we have to connect through a socket port.

The main objective of this socket programming tutorial is to get introduce you how socket server and client communicate with each other. You will also learn how to write python socket server program.

Python Socket Example

We have said earlier that a socket client requests for some resources to the socket server and the server responds to that request.

So we will design both server and client model so that each can communicate with them. The steps can be considered like this.

  1. Python socket server program executes at first and wait for any request
  2. Python socket client program will initiate the conversation at first.
  3. Then server program will response accordingly to client requests.
  4. Client program will terminate if user enters “bye” message. Server program will also terminate when client program terminates, this is optional and we can keep server program running indefinitely or terminate with some specific command in client request.

Python Socket Server

We will save python socket server program as socket_server.py. To use python socket connection, we need to import socket module.

Then, sequentially we need to perform some task to establish connection between server and client.

We can obtain host address by using socket.gethostname() function. It is recommended to user port address above 1024 because port number lesser than 1024 are reserved for standard internet protocol

import socket


def server_program():
    # get the hostname
    host = socket.gethostname()
    port = 5000  # initiate port no above 1024

    server_socket = socket.socket()  # get instance
    # look closely. The bind() function takes tuple as argument
    server_socket.bind((host, port))  # bind host address and port together

    # configure how many client the server can listen simultaneously
    server_socket.listen(2)
    conn, address = server_socket.accept()  # accept new connection
    print("Connection from: " + str(address))
    while True:
        # receive data stream. it won't accept data packet greater than 1024 bytes
        data = conn.recv(1024).decode()
        if not data:
            # if data is not received break
            break
        print("from connected user: " + str(data))
        data = input(' -> ')
        conn.send(data.encode())  # send data to the client

    conn.close()  # close the connection


if __name__ == '__main__':
    server_program()

So our python socket server is running on port 5000 and it will wait for client request. If you want server to not quit when client connection is closed, just remove the if condition and break statement. Python while loop is used to run the server program indefinitely and keep waiting for client request.

Python Socket Client

We will save python socket client program as socket_client.py. This program is similar to the server program, except binding.

The main difference between server and client program is, in server program, it needs to bind host address and port address together.

See the below python socket client example code, the comment will help you to understand the code.


import socket


def client_program():
    host = socket.gethostname()  # as both code is running on same pc
    port = 5000  # socket server port number

    client_socket = socket.socket()  # instantiate
    client_socket.connect((host, port))  # connect to the server

    message = input(" -> ")  # take input

    while message.lower().strip() != 'bye':
        client_socket.send(message.encode())  # send message
        data = client_socket.recv(1024).decode()  # receive response

        print('Received from server: ' + data)  # show in terminal

        message = input(" -> ")  # again take input

    client_socket.close()  # close the connection


if __name__ == '__main__':
    client_program()

Python Socket Programming Output

To see the output, first run the socket server program. Then run the socket client program. After that, write something from client program. Then again write reply from server program. At last, write bye from client program to terminate both program. Below short video will show how it worked on my test run of socket server and client example programs

pankaj$ python3.6 socket_server.py 
Connection from: ('127.0.0.1', 57822)
from connected user: Hi
 -> Hello
from connected user: How are you?
 -> Good
from connected user: Awesome!
 -> Ok then, bye!
pankaj$
 

pankaj$ python3.6 socket_client.py -> Hi Received from server: Hello -> How are you? Received from server: Good -> Awesome! Received from server: Ok then, bye! -> Bye pankaj$


Related Solutions

I am trying to write a UDP socket program in which there is a server program...
I am trying to write a UDP socket program in which there is a server program and a client program. This is what I have but I can't figure out where I am going wrong. This is the input and expected output: > gcc udpclient.c –o clientout > gcc udpserver.c –o serverout > ./serverout 52007 ‘to celebrate’ & > ./clientout odin 52007 ‘Today is a good day’ Today is a good day to celebrate //UDP echo client program #include #include...
Socket-based Java server program
Write a Socket-based Java server program that responds to client messages as follows: When it receives a message from a client, it simply converts all the letters into ASCII characters and sends back them to the client. Write both client and server programs demonstrating this.
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...
Write a python program that will allow a user to draw by inputting commands. The program...
Write a python program that will allow a user to draw by inputting commands. The program will load all of the commands first (until it reaches command "exit" or "done"), and then create the drawing. Must include the following: change attributes: color [red | green | blue] width [value] heading [value] position [xval] [yval] drawing: draw_axes draw_tri [x1] [y1] [x2] [y2] [x3] [y3 draw_rect [x] [y] [b] [h] draw_poly [x] [y] [n] [s] draw_path [path] random random [color | width...
. Draw and explain any socket-related activity of the client and server that communicates over the...
. Draw and explain any socket-related activity of the client and server that communicates over the UDP and TCP
Write a c++ Program To simulate the messages sent by the various IoT devices, a text...
Write a c++ Program To simulate the messages sent by the various IoT devices, a text le called device data.txt is provided that contains a number of device messages sent, with each line representing a distinct message. Each message contains a device name, a status value and a Unix epoch value which are separated by commas. Your c++ program will read this le line by line. It will separate the message into device name, status value and epoch value and...
Client AND server using names pipes (mkfifo) in C/C++ Write and client program that will talk...
Client AND server using names pipes (mkfifo) in C/C++ Write and client program that will talk to a server program in two separate terminals. Write the server program that can handle multiple clients (so threads will be needed) and with fork() and exec()
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()
A study finds that graduate students send a mean of 74 text messages per day with...
A study finds that graduate students send a mean of 74 text messages per day with a standard deviation of 15.2 text message per day while undergraduate students send a mean of 116 text messages per day with a standard deviation of 26.51. Which group, the undergraduate students or the graduate students have more variation in the number of sent text messages? Undergraduates, because their standard deviation is higher Undergraduates, because their standard deviation is lower Graduate students, because their...
1. A survey of 1000 drivers found that 29% of the people send text messages while...
1. A survey of 1000 drivers found that 29% of the people send text messages while driving. Last year, a survey of 1000 drivers found that 17% of those sent text messages while driving. (Show your work without using software to solve) a. Give a 95% confidence interval for the increase in text messaging while driving. b. At α = .05, can we conclude that there has been an increase in the number of drivers who text while driving? State...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT