用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

用SocketServer类实现时间戳服务器和客户端

2013-02-01 作者: sam_linux举报

[python]代码库

  程序逻辑:导入服务器类-->定义主机常量-->请求处理类-->启动代码
  1 #! /usr/bin/env python
  2 #服务器程序
  3 from SocketServer import (TCPServer as TCP,
  4     StreamRequestHandler as SRH)
  5 from time import ctime
  6
  7 HOST = ''
  8 PORT = 21567
  9 ADDR = (HOST,PORT)
 10
 11 class MyRequestHandler(SRH):
 12     def handle(self):
 13         print '...connected from:',self.client_address
 14         self.wfile.write('[%s] %s' % (ctime(),
 15             self.rfile.readline()))
 16
 17 tcpServ = TCP(ADDR,MyRequestHandler)
 18 print 'waiting for connection...'
 19 tcpServ.serve_forever()
 20 
 ==============================================================
  1 #! /usr/bin/env python
  2 #客户端程序
  3 from socket import *
  4
  5 HOST = '192.168.1.190'
  6 PORT = 21567
  7 BUFSIZ = 1024
  8 ADDR = (HOST,PORT)
  9
 10 while True:
 11     tcpCliSock = socket(AF_INET,SOCK_STREAM)
 12     tcpCliSock.connect(ADDR)
 13     data = raw_input('> ')
 14     if not data:
 15         break
 16     tcpCliSock.send('%s\r\n' % data)
 17     data = tcpCliSock.recv(BUFSIZ)
 18     if not data:
 19         break
 20     print data.strip()  #剥掉行结束符\r\n
 21     tcpCliSock.close()
 22
=====================================================================
服务器端运行
++++++++++++++++
[root@dogood core16]# python TsTservs.py    
waiting for connection...
...connected from: ('192.168.1.110', 4601)
...connected from: ('192.168.1.110', 4602)
...connected from: ('192.168.1.110', 4603)
客户端运行
++++++++++++++++
>>> =========================== RESTART ===========================
>>>
> hello
[Thu Jan 31 06:25:22 2013] hello
> nihao
[Thu Jan 31 06:25:25 2013] nihao
>
>>>


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...