I am a complete beginner to network programming. I have an assignment that asks me to;

CLIENT prompts for a string S from the user. The client then splits the string S, assumed to be of length n, into two strings S1 and S2 that are of equal length n/2 if n is even, or of lengths (n + 1)/2 and (n − 1)/2 respectively if n is odd. The client then: 1. sends S1 and S2 to the server in two distinct UDP packets; 2.waits for a string R from the server, in another UDP packet; 3.checks if R is equal to the concatenation of S2 and S1; 4.displays the result of the final test to the user.

SERVER constantly waits for UDP messages. The server waits for a sequence of two distinct UDP messages containing strings S1 and S2. The server then: 1. receives S1 followed by S2 in two different UDP packets; 2. constructs R as the concatenation of S2 followed by S1; 3. sends R to the client as a UDP packet; 4. starts again.

import socket 
import sys

HOST = "localhost" 
PORT = 9999 

s = input("Enter a string S: ")
n = len(s)

if (n%2) == 0:
    s1 = s[:(n//2)]
    s2 = s[(n//2):]
    print("String s1 is: "+s1)
    print("String s2 is: "+s2)
    s1 = s[:(n + 1)//2]
    s2 = s[(n + 1)//2:]
    print("String s1 is: "+s1)
    print("String s2 is: "+s2)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
sock.sendto(s1.encode() ,(HOST, PORT))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(s2.encode() ,(HOST, PORT))

received = sock.recv(1024)

if received == s2 + s1:
    print("Sent: "+ s2 + s1) 
    print("Received: "+received)


import socketserver
class MyUDPHandler(socketserver.DatagramRequestHandler):
    def handle(self): 
        data1 = self.request[0]
        data2 = self.request[0]
        print("Wrote :")
        result = data2 + data 1
        self.request[1].sendto(result, self.client_address)

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    server = socketserver.UDPServer((HOST, PORT), MyUDPHandler)

The code works very poorly. It doesn't give me s2 + s1. It only manages to split the string S correctly. I don't know what is going wrong. Any help is really appreciated.

0 Answers