Python: Kirim via TCP dan di parsing

From OnnoWiki
Jump to navigation Jump to search

client.py

import sys
import time
import socket
import random

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

# Connect the socket to the port where the  server is listening
server_address = ('192.168.0.100', 2000)
sock.connect(server_address)

try:
    for i in xrange(100):
       m0 = random.random()
       m1 = random.random()
       message = "%1.4f" % m0  + " %1.4f" % m1
       print >>sys.stderr, 'sending ' , message
       sock.sendall(message)
       time.sleep(0.5)

finally:

   print >>sys.stderr, 'closing socket'
   sock.close()


server.py

import sys
import time
import datetime
import socket
from bokeh.plotting import figure, output_server, show, cursession

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

# Bind the socket to the port

server_address = ('192.168.0.100', 2000)

print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print >>sys.stderr, 'waiting for a connection'
    connection, client_address = sock.accept()

    try:
        print >>sys.stderr, 'connection  from', client_address

        while True:
            data = connection.recv(20).split()
            print data[0] + "  " + data[1] + "\n"

            if len(data) == 0:
               break 

            time.sleep(0.01)

    finally:
        # Clean up the connection
        connection.close()