Trying UDP Server & Client Classes in Same File but UDP Client not Sending Message

Viewed 18

I've been tinkering around with a UDP Server/Client example from pythontic.com (all credit goes to them for the original code) and have been trying to integrate the server and client in classes and run them in the same file. However, the Client's messages aren't received by the Server: class Server(): def init(self): True def trysend(self): import socket

    localIP = "127.0.0.1"

    localPort = 20001

    bufferSize = 1024

    msgFromServer = "Hello UDP Client"

    bytesToSend = str.encode(msgFromServer)

    # Create a datagram socket

    UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

    # Bind to address and ip

    UDPServerSocket.bind((localIP, localPort))

    print("UDP server up and listening")

    # Listen for incoming datagrams

    while (True):
        bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)

        message = bytesAddressPair[0]

        address = bytesAddressPair[1]

        clientMsg = "Message from Client:{}".format(message)
        clientIP = "Client IP Address:{}".format(address)

        print(clientMsg)
        print(clientIP)

        # Sending a reply to client

        UDPServerSocket.sendto(bytesToSend, address)

class Client(): def int(self): True def tryreceive(self): import socket

    msgFromClient = "Hello UDP Server"

    bytesToSend = str.encode(msgFromClient)

    serverAddressPort = ("127.0.0.1", 20001)

    bufferSize = 1024

    # Create a UDP socket at client side

    UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

    # Send to server using created UDP socket

    UDPClientSocket.sendto(bytesToSend, serverAddressPort)

    msgFromServer = UDPClientSocket.recvfrom(bufferSize)

    msg = "Message from Server {}".format(msgFromServer[0])

    print(msg)

test1= Server.trysend(True) test2= Client.tryreceive(True)

If anyone could tell me why this isn't working or how to fix it, I'd appreciate it greatly. Thank you.

0 Answers
Related