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 # 返回函数运行结果
Client 端发消息
while True:
cmd = raw_input("respond")
if cmd == "exit":
break
elif len(cmd) == 0:
continue
s.send(cmd)
date = s.recv(1024)
print ("rec:",date)
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 上接受数据
if not data_r:
break #若已连接的client端断开,退出
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 方法.