python socket recv 阻塞_Python socket编程(阻塞) --基于SocketServer

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值