Created
June 24, 2011 17:22
-
-
Save lunr/1045244 to your computer and use it in GitHub Desktop.
Python: Multi-threaded JSON Echo Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* | |
* PHP JSON Echo Server client | |
* | |
*/ | |
// python server socket | |
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); | |
socket_connect($socket, 'localhost', 5555); | |
//Create a message, and send it to the server on $socket. | |
$data = array( | |
'username' => 'sysadmin', | |
'key' => '093ufj408xr0289u3r0x9u2m309x', | |
'action' => 'login', | |
); | |
$json = json_encode($data); | |
socket_send($socket, $json, strlen($json), MSG_EOF); | |
$data = socket_read($socket, 65535); | |
$object = json_decode($data); | |
if($object->status) { | |
echo '<p>Data received successfully.'; | |
} else { | |
echo '<p>Error. Data not read correctly!'; | |
} | |
echo '<p>'.$data; | |
//Close the socket. | |
socket_close($socket); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# a simple multi-threaded TCP Echo server | |
from socket import * | |
import threading | |
import thread | |
import time | |
import json | |
def handler(clientsock,addr): | |
while 1: | |
time.sleep(2) | |
data = clientsock.recv(65535); | |
if not data: | |
break | |
object = json.loads(data) | |
object['status'] = 1 | |
object['timestamp'] = time.time() | |
output = json.dumps(object) | |
msg = output | |
clientsock.send(msg) | |
clientsock.close() | |
if __name__ == '__main__': | |
HOST = 'localhost' | |
PORT = 5555 | |
BUFSIZ = 65535 | |
ADDR = (HOST, PORT) | |
serversock = socket(AF_INET, SOCK_STREAM) | |
serversock.bind(ADDR) | |
serversock.listen(5) | |
while 1: | |
print 'waiting for connection...' | |
clientsock, addr = serversock.accept() | |
print '...connected from: ', addr | |
thread.start_new_thread(handler, (clientsock, addr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment