SocketServer模块是Python对socket常规通信的一个经过封装的模块,使用简单,基于面向对象的设计模式,但功能有限,可用于快速开发。
Tips:
默认端口:6767
默认本地ip:127.0.0.1
代码样例:
1. 服务端:
#!/usr/bin/env python
# encoding: utf-8
from SocketServer import (TCPServer as TCP,StreamRequestHandler as SRH)
import sys
import os
from time import ctime
reload(sys)
sys.setdefaultencoding("utf-8")
conn_flag = False #连接提示标识,规定只显示一次
class myWebServer(SRH):
def handle(self):
global conn_flag
if conn_flag == False:
print "[*]Connect from: ",self.client_address
conn_flag = True
buf = self.rfile.readline()
self.wfile.write("[%s] %s" % (ctime(),buf))
print "[%s] %s" % (ctime(),buf)
def main():
HOST = "127.0.0.1"
PORT = 6767
Server = TCP((HOST,PORT), myWebServer)
print "Waiting for the Connection..."
try:
Server.serve_forever()
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
print "[-]Client may be offLine"
sys.exit(-1)
if __name__ == '__main__':
main()
2. 客户端
#!/usr/bin/env python
# encoding: utf-8
import socket
import os
import sys
import time
import traceback
reload(sys)
sys.setdefaultencoding("utf-8")
def SocketInit():
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except Exception as e:
sys.exit(-1)
return s
def Conn(s,host,port):
while 1:
try:
s.connect((host,port))
except Exception as e:
time.sleep(2)
else:
break
def main():
host = "127.0.0.1"
port = 6767
try:
while 1:
sC = SocketInit()
Conn(sC, host, port)
Str_buffer = raw_input(host+":"+str(port)+">")
Str_buffer += "\r\n"
try:
sC.send(Str_buffer)
except Exception as e:
print "[-]Can not send Data"
else:
recv_buffer = sC.recv(1024)
if not recv_buffer:
print "[-]Server is Off"
else:
print recv_buffer
except KeyboardInterrupt:
sC.close()
sys.exit(0)
if __name__ == '__main__':
main()