码迷,mamicode.com
首页 > 编程语言 > 详细

Python socket (单线程)

时间:2016-06-19 15:29:50      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

client, 客户端 code :

    客户端主要方法, s.send(); s.sendall(); s.recv(); s.connect()

class Client(object):

  def __init__(self, ip, PortNo=XXX):
  self.ip = ip
  self.PortNo = PortNo

  def connect_socket(self):
   count = 1
  status = 0
  while count < 6 and status == 0: # 尝试5次 在 ip::PortNo 上创建socket 链接.
   print ("Attempt %s time(s) to open socket port" % count)
  try:
  self.soct = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定义socket 类型(TCP)
  except socket.error, e: # socket error 异常处理, 这里把异常catch住,代码可以继续运行. 函数结尾返回一个函数运行结果标志位,供main函数或者调用函数判断.
  print ("error occur during creating socket: : %s" % e)
  try:
  self.soct.connect((self.ip, self.PortNo))
  status = 1
  print ("Socket opened success: %s :: %s" % (self.ip, self.PortNo))
  except socket.error, e: # 常见 socket error 有 目标地址错误,PortNo 被占用, 防火墙 等原因
  print ("Address or port related error detected during connect to server: : %s" % e)
  count += 1
  time.sleep(3)
  if status == 0:
  return False
  return True # 返回函数运行结果



server, 服务端code,

    服务端主要方法, s.recv();   s.send();   s.sendall();    s.bind();   s.close()

class Server(object):
def __init__(self, ip, PortNo=XXX):
self.ip = ip
self.PortNo = PortNo
def run_server(self):
  self.soct = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定义socket 类型(TCP)
  self.scot.bind((self.ip,self.PortNo))
  self.soct.listen(1) # socket 监听的数量.
  conn,addr = self.soct.accept() # 接受 scoket 链接请求.
print("Socket has been established with %s :: %s" % (conn,addr))
  while True:
    data_r = self.soct.recv(1024) # 从socket 上接受数据
    print("Received %s from socket" % data_r)
    self.soct.sendall("data_s") # 向socket 发送数据
    print("Send data %s to socket" % data_s)  
  self.soct.close() # 结束所建立的 socket 方法.




Python socket (单线程)

标签:

原文地址:http://www.cnblogs.com/zzyzz/p/5581503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!