这此实验非常简单,但由于还久没用java了,对java网络编程不熟悉,只好各种查资料,才写出来了。
实验的要求是:编写两个计算机程序,第一个程序模拟发送方,首先从界面读取待发送字符(每次接收一个字符的输入),然后等待接收方应答;第二个程序模拟接收方,模拟接收状态a.Ackà接收到该字符,b.NAKà校验错误,丢弃,c.无反应à数据帧丢失,模拟超时。
发送方根据接收方的应答进行相应的处理,如果发送方收到的是b(或c超时),则重传该字符,否则继续接收用户的输入。要求单机测试之后在双机上进行验证。提示:可以在接收方设置随机函数来模拟停等协议的丢包。
<pre name="code" class="java">import java.util.*;
import java.net.*;
import java.io.*;
public class UDPSender{
//private static final int TIMEOUT=3000;
public static void main(String[] args) throws Exception{
int TIMEOUT=30000;
DatagramSocket ds = null;
DatagramPacket dp1 = null;
DatagramPacket dp2 = null;
byte[] buf1 = new byte[1024];
byte[] buf2 = new byte[1024];
ds = new DatagramSocket(3000);
System.out.println("开始发送数据");
int i = 0;
String send =new String();
while(true){
Scanner scan = new Scanner(System.in);
System.out.println("请输入传送的字符");
send = "";
send += i;
send += scan.next();
buf1 = send.getBytes();
dp1 = new DatagramPacket(buf1,send.length(),InetAddress.ge