0

我正在尝试设置一个程序来查看我的网络上数据包的 UDP 性能和响应时间。我有一个客户端和服务器端类,我正在为此指定要发送文本的数据包大小。例如,如果我想在一个 4 字节的数据包中发送一个单词“Tester”,它将发送“TEST”部分,但不会在单词的其余部分重复。我试图添加一个while循环,但我认为我所拥有的不正确,因为它连续发送前4个字节。有谁知道我需要什么样的循环以及应该将它放在哪里以获得我想要的结果?客户端的代码如下。非常感谢您的任何指导。

//UDP Client
//Usage: java UDPClient [server addr] [server port]

import java.io.*;
import java.net.*;

public class UDPClient extends variable {

   // static Integer portNo = 4444;
    static Integer byteSize = 4;

    public static void main(String[] args) throws Exception {
      SocketForm form = new SocketForm();

      long startTime; // Starting time of program, in milliseconds.
      long endTime;   // Time when computations are done, in milliseconds.
      double time;  

        //get server address
        String serverName = "localhost";

        if (args.length >= 1)
            serverName = args[0];
      InetAddress serverIPAddress = InetAddress.getByName(serverName);

        //get server port;
        int serverPort = form.cliportNo;
        if (args.length >= 2)
            serverPort = Integer.parseInt(args[1]);
        //create socket
        DatagramSocket clientSocket = new DatagramSocket();
        //get input from keybaord
        byte[] sendData = new byte[byteSize];
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader (System.in));
        while (true){ //incorrect as it is only repeating the first four bytes of the word typed in the console
        String sentence = inFromUser.readLine();
        startTime = System.currentTimeMillis();
        sendData = sentence.getBytes();
        //construct and send datagram;

        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, serverPort);
        clientSocket.send(sendPacket);

        //receive datagram
        byte[] receiveData = new byte [byteSize];

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        //print output
        String sentenceFromServer = new String(receivePacket.getData());
        System.out.println("From Server:" + sentenceFromServer);

        //close client socket
                //clientSocket.close();
        endTime = System.currentTimeMillis();
        time = endTime - startTime;
        //System.out.println("Time :" + time);
        }
    } //end of main
} //end of UDPClient
4

1 回答 1

0

你的意思是这样吗?

private void sendChunked( String msg, int chunkSizeInBytes ) {
   byte[] msgBytes = msg.getBytes();
   for( int index = 0; index < msgBytes.length ; index += chunkSizeInBytes ) {
         DatagramPacket packet = new DatagramPacket( msgBytes, index, Math.min( chunkSizeInBytes, msgBytes.length-index ));
         send( packet ); // You know how that works ...
   }
}
于 2013-10-18T13:16:41.540 回答