1 client, 客户端 code : 2 3 客户端主要方法, s.send(); s.sendall(); s.recv(); s.connect() 4 5 class Client(object): 6 7 def __init__(self, ip, PortNo=XXX): 8 self.ip = ip 9 self.PortNo = PortNo 10 11 def connect_socket(self): 12 count = 1 13 status = 0 14 while count < 6 and status == 0: # 尝试5次 在 ip::PortNo 上创建socket 链接. 15 print ("Attempt %s time(s) to open socket port" % count) 16 try: 17 self.soct = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定义socket 类型(TCP) 18 except socket.error, e: # socket error 异常处理, 这里把异常catch住,代码可以继续运行. 函数结尾返回一个函数运行结果标志位,供main函数或者调用函数判断. 19 print ("error occur during creating socket: : %s" % e) 20 try: 21 self.soct.connect((self.ip, self.PortNo)) 22 status = 1 23 print ("Socket opened success: %s :: %s" % (self.ip, self.PortNo)) 24 except socket.error, e: # 常见 socket error 有 目标地址错误,PortNo 被占用, 防火墙 等原因 25 print ("Address or port related error detected during connect to server: : %s" % e) 26 count += 1 27 time.sleep(3) 28 if status == 0: 29 return False 30 return True # 返回函数运行结果 31 32
1 Client 端发消息 2 3 while True: 4 cmd = raw_input("respond") 5 if cmd == "exit": 6 break 7 elif len(cmd) == 0: 8 continue 9 s.send(cmd) 10 date = s.recv(1024) 11 print ("rec:",date)
1 server, 服务端code, 2 3 服务端主要方法, s.recv(); s.send(); s.sendall(); s.bind(); s.close() 4 5 class Server(object): 6 def __init__(self, ip, PortNo=XXX): 7 self.ip = ip 8 self.PortNo = PortNo 9 def run_server(self): 10 self.soct = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定义socket 类型(TCP) 11 self.scot.bind((self.ip,self.PortNo)) 12 self.soct.listen(1) # socket 监听的数量. 13 conn,addr = self.soct.accept() # 接受 scoket 链接请求. 14 print("Socket has been established with %s :: %s" % (conn,addr)) 15 while True: 16 data_r = self.soct.recv(1024) # 从socket 上接受数据 17 if not data_r: 18 break #若已连接的client端断开,退出 19 print("Received %s from socket" % data_r) 20 self.soct.sendall("data_s") # 向socket 发送数据 21 print("Send data %s to socket" % data_s) 22 self.soct.close() # 结束所建立的 socket 方法.