开发者

Python server for hosting sockets and reading data

开发者 https://www.devze.com 2023-01-24 12:02 出处:网络
I\'m trying to create a python server that will serve calls from outer source through sockets. So I\'ve skimmed through the docs and copied this code, I can connect but no sent data is shown. What am

I'm trying to create a python server that will serve calls from outer source through sockets. So I've skimmed through the docs and copied this code, I can connect but no sent data is shown. What am I doing wrong ?

import SocketServer

class MyUDPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        self.data = self.rfile.readline().strip()
        print "%s wrote:" % self.client_address[0]
        print self.data
        self.wfile.write(self.data.upper())

if __name开发者_运维百科__ == "__main__":
    HOST, PORT = "localhost", 80
    try:
        server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
        print("working")
        server.serve_forever()
        serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        serversocket.bind((socket.gethostname(), 80))
        serversocket.listen(5)     
    except:
        print("not working")

    while True:
        (clientsocket, address) = serversocket.accept()
        ct = client_thread(clientsocket)
        ct.run()

class mysocket:
    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host, port):
        self.sock.connect((host, port))

    def mysend(self, msg):
        totalsent = 0
        while totalsent < MSGLEN:
            sent = self.sock.send(msg[totalsent:])
            if sent == 0:
                raise RuntimeError("socket connection broken")
            totalsent = totalsent + sent

    def myreceive(self):
        msg = ''
        while len(msg) < MSGLEN:
            chunk = self.sock.recv(MSGLEN-len(msg))
            if chunk == '':
                raise RuntimeError("socket connection broken")
            msg = msg + chunk
        return msg

And moreover, if this code is proper - how to use it ? I'm just setting the server now with python server.py which creates an instance of MyUdpHandler but what next ?


you problem might lie in that server.serve_forever() never returns, it will block your code and nothing beyond it will run.

you might have this work better by splitting this across threads:

import threading
def launch_server():
    server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
    print("working")
    server.serve_forever()

#carry on with your other code here.


#this belongs at the _bottom_ of your file! not the middle!
if __name__ == '__main__':
    server_thread = threading.Thread(target=launch_server, args=())
    server_thread.start()
0

精彩评论

暂无评论...
验证码 换一张
取 消