课程名称: 考核日期:
过程性考核作业:
使用socket编程中的UDP,在应用层实现可靠数据传输,并自己设计验证方案,根据你实现的程度达到的效果和验证的合理性给予成绩,实现的程度包括所达到的程度如rdt1.0,2.0,3.0,gbn,sr,tcp来作为你所实现的深度,验证效果自己通过代码模拟错误,并观察你所实现的可靠数据传输算法能否恢复出来。
TCP服务器代码:
import socket
ip_port = ('127.0.0.1', 10001)
sock = socket.socket()
sock.bind(ip_port)
sock.listen(2)
while True:
print('服务器等待...')
conn, address = sock.accept()
client_data = conn.recv(1024)
print(client_data.decode())
message = input('发送:')
conn.sendall(str('服务器:' + message).encode())
conn.close()
运行结果如下图所示:
TCP客户端代码:
import socket
ip_port = ('127.0.0.1', 10001)
while True:
sock = socket.socket()
sock.connect(ip_port)
message = input('发送:')
sock.sendall(str('客户端:' + message).encode())
print('客户端等待...')
server_reply = sock.recv(1024)
print(server_reply.decode())
sock.close()
运行结果如下图所示:
发送数据运行结果如下图所示:
UDP服务器代码:
import socket
def main():
PORT = 8000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
address = ("127.0.0.1", PORT)
server_socket.bind(address)
while True:
print('服务器等待...')
receive_data, client_address = server_socket.recvfrom(1024)
print("客户机:" + str(receive_data.decode()))
msg = input("发送:")
server_socket.sendto(msg.encode(), client_address)
udp_socket.close()
if __name__ == "__main__":
main()
运行结果如下图所示:
UDP客户端代码:
import socket
def main():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
message = input("发送:")
if message == "exit":
break
server_address = ("127.0.0.1", 8000)
client_socket.sendto(message.encode(), server_address)
print('客户端等待...')
receive_data, sender_address = client_socket.recvfrom(1024)
print("服务器:" + str(receive_data.decode()))
client_socket.close()
if __name__ == '__main__':
main()
运行结果如下图所示:
发送数据运行结果如下图所示: