Overclock.net - An Overclocking Community - View Single Post - Does python have networking?

View Single Post
post #5 of (permalink) Old 09-15-2015, 11:26 AM
Mrzev
New to Overclock.net
 
Mrzev's Avatar
 
Join Date: Feb 2008
Location: Texas
Posts: 2,258
Rep: 96 (Unique: 76)
Whenever i need to listen to a port for data and do something with it, I tend to go with python because it's pretty quick and easy. This script listens to port 5555 and writes the data into an SQL db.

Code:
#!/usr/bin/python
import socket
import sys
import json
import mysql.connector
from datetime import datetime

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('', 5555)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)

print >>sys.stderr, 'Started - Listening'
while True:
        # Wait for a connection
        
        message = ""
        connection, client_address = sock.accept()
        try:
                print >>sys.stderr, 'connection from', client_address
                while True:
                        #Loops trough 1KB at a time until it received all the data.
                        data = connection.recv(1024)
                        message += data
                        if not data:                            
                                print message
                                print " "
                                jdata = json.loads(message)
                                
                                cnx = mysql.connector.connect(user='', password='',
                                                                  host='127.0.0.1',
                                                                  database='test')
                                cursor = cnx.cursor()
                                type= jdata["MovementForward"][0]["Device"]["type"]
                                name = jdata["MovementForward"][0]["Device"]["name"]
                                x= jdata["MovementForward"][0]["Device"]["movements"][0]["Movement"]["points"][3]["PointLoc"]["x"]
                                y= jdata["MovementForward"][0]["Device"]["movements"][0]["Movement"]["points"][3]["PointLoc"]["y"]
                                date_object = datetime.strptime(jdata["MovementForward"][0]["Device"]["movements"][0]["Movement"]["date"], '%Y-%m-%dT%H:%M:%S+0000')

                                cursor.execute("INSERT INTO locations (type,name,x,y,dateReceived) VALUES (%s, %s, %s, %s, %s)",(type, name,x,y,date_object))
                                cnx.close()
                                
                                break
        finally:
                connection.close()




Mrzev is offline