python py3k 开发socket服务

import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("%s wrote:" % self.client_address[0])
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.send(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

来自官方帮助文档的代码,后面的是PY2.7的代码

#! /usr/bin/env python
# -*- coding:UTF-8 -*-
import SocketServer
class RequestHandler(SocketServer.StreamRequestHandler):
  def handle(self):
    mdata="";
    while True:
      nowData = self.request.recv(1024)
      if nowData=="rn":
          self.request.send("hi:"+mdata+"rn")
          #self.request.close() 开这行主动关闭连接 不过测试的时候服务器端
          #有错误提示 程序还是可以正常运行
      else:
          mdata=''.join(nowData)
            
hostname = '192.168.1.100'
port = 43
server = SocketServer.ThreadingTCPServer((hostname, port), RequestHandler)
server.serve_forever()

发表评论

电子邮件地址不会被公开。 必填项已用*标注