基于UDP的可靠通信协议

之前的一个小项目中涉及到网络通信。当时也不太懂,随便弄了个udp广播,这次算是填坑了。

设计了一个基于UDP的可靠通信协议,包括发送后等待回复,超时重发,超时间隔加倍等等,

为什么不用tcp呢,为了学习—_—

 1 import socket
 2 import json
 3 
 4 class otp:  # own transaction protocal
 5 
 6     def __init__(self,port):
 7         self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 8         self.sendnum = 0
 9         address = ('127.0.0.1',port)
10         self.s.bind(address)
11 
12     def send(self,address,msg,t =0.25):
13         if t > 1:
14             self.s.settimeout(None)
15             return False
16         json_string = json.dumps((self.sendnum,msg))
17         self.s.sendto(json_string,address)
18         self.s.settimeout(t)
19         try:
20             while True:
21                 recvmsg, recaddr = self.s.recvfrom(2048)
22                 try:
23                     a =int(recvmsg)
24                     if (recaddr == address) & (a == self.sendnum):
25                         self.s.settimeout(None)
26                         return True
27                     else:
28                         self.sendnum += 1
29                         self.send(address, msg, t * 2)
30                 except Exception as e:
31                     pass
32 
33         except Exception as e:
34             self.sendnum += 1
35             self.send(address,msg,t*2)
36 
37     def recv(self):
38         recvmsg, recaddr = self.s.recvfrom(2048)
39         msg = json.loads(recvmsg)
40         self.s.sendto(str(msg[0]),recaddr)
41         return (msg[1],recaddr)
42 
43 
44     def close(self):
45         self.s.close()
service.py

from protocol import otp

if __name__ == '__main__':
    port = 12344
    s = otp(port)
    while True:
        (recvmsg, recaddr) = s.recv()
        print recvmsg+str(recaddr)
        if not s.send(recaddr,"ok"):
            print "Log: Error "+recvmsg+str(recaddr)
        else:
            print "Log: ok!"


client.py

from protocol import otp

if __name__ == '__main__':
    port = 12345
    address = ('127.0.0.1',12344)
    s = otp(port)
    while True:
        line = raw_input()
        if line:
            if s.send(address,line):
                print 'ok'
                print s.recv()
            else:
                print "Could not connection server!"

 

posted @ 2017-04-24 23:58  爱吃土豆的男孩  阅读(510)  评论(0编辑  收藏  举报