Arthur
Arthur

Reputation: 86

is it possible to communicate through socket with django

Hello i have a server program in python

built with socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

I have to make a web application for the users. the web application must send a string to the server. my question is : Can i use django to build a web application, and send a string to the python server ? thank you for reading.

Upvotes: 0

Views: 674

Answers (1)

username
username

Reputation: 606

Yes, the clients will be communicating with Django server via TCP connection by WSGI protocol and some server-side code will be establishing UDP-connection with your Python server.

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005

# django view
def send_string_to_udp_server_view(request):
    message = request.GET.get('message')  # message presumably sent as query string
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(message, (UDP_IP, UDP_PORT))
    sock.close()

PS: for simplicity sake the code lacks all the checks and exceptions handling.

Upvotes: 1

Related Questions