Python 的 Socket 编程多线程教程

server

import socket  
import threading  
import SocketServer  
import json, types,string  
import os, time  




#server handler
def test(self):
    return HttpResponse(self.request.META['REMOTE_ADDR'])  

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):  
    def handle(self):  
        data = self.request.recv(1024)
        jdata = json.JSONDecoder().decode(data)  
        print "Client : '%r'"% jdata['content']
        
            
        jresp = json.JSONEncoder().encode(jdata)
        self.request.sendall(jresp)
        
       
   
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):  
    pass  
  
if __name__ == "__main__":  
    # Port 0 means to select an arbitrary unused port 
    #print test()
    HOST, PORT = "localhost", 50001  
      
    SocketServer.TCPServer.allow_reuse_address = True  
    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)  
    ip, port = server.server_address  
  
    # Start a thread with the server -- that thread will then start one  
    # more thread for each request  
    server_thread = threading.Thread(target=server.serve_forever)  
  
    # Exit the server thread when the main thread terminates  
    server_thread.daemon = True  
    server_thread.start()  
    print "Server loop running in thread:", server_thread.name  
    print " .... waiting for connection"  
  
    # Activate the server; this will keep running until you  
    # interrupt the program with Ctrl-C  
    server.serve_forever()  

client

import socket
import threading  
import SocketServer  
import json  

#HeartBeat  and the Inational
def client(ip, port, message):  
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)
    except socket.error, msg:
        print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
        sys.exit();         

    try:
        remote_ip = socket.gethostbyname( ip )

    except socket.gaierror:
        #could not resolve
        print 'Hostname could not be resolved. Exiting'
        sys.exit()
    try:
        sock.connect((ip, port))    
        print "Client: {}".format(message)
        try:
            content_msg={'content':message}
            json_msg=json.JSONEncoder().encode(content_msg)            
            sock.sendall(json_msg) 
        except socket.error:
            #Send failed
            print 'Send failed'
            sys.exit()                  
        response = sock.recv(1024) 
        if len(response)!=0: 
            jresp = json.JSONDecoder().decode(response)
            #jresp = json.loads(response) 

            print "Server: ",jresp['content']
            return jresp
        else:

            return False         
        sock.close()

        #print jresp[0]['src']
    except:  
        print 'Connect failed'


client('localhost', 50001, 'ddddddd')


你可能感兴趣的:(Python 的 Socket 编程多线程教程)