1

我想知道如何将一条消息分成 15 个字符的多条消息并通过 udp 连接发送。我怎样才能让要发送的第一条消息是数据包的数量(要发送的消息)我现在只能发送一个数据包

public class MainTalker extends Activity 
{
    private static DatagramSocket socket;
    private static DatagramPacket packet;
    private static Thread send;
    private Button cl1;
    private static EditText ed1;
    private static String msg = "Message";
    private static byte[] data = new byte[15];
    private static String TAG = "Sender UDP";
    static int count=0;
    static String[] output = new String[100] ;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_talker);

        ed1 = (EditText) findViewById(R.id.msg);
        cl1 = (Button) findViewById(R.id.send);

        try {
            socket = new DatagramSocket(11001);
            Toast toast = Toast.makeText(getApplicationContext(),"Port Opened",Toast.LENGTH_SHORT);
            toast.show();
            System.out.println("Port Opened ");
            socket.setBroadcast(true);
        } catch (Exception e) {
            System.out.println("Exception: Port not opened");
            e.printStackTrace();
            Log.e(TAG, e.getMessage());
        }

        cl1.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
                System.out.println("Button Clicked ");

                send = new sendthr();
                send.start();
            }
        });
    }

    private static class sendthr extends Thread {
        public void run()
        {
                System.out.println("Thread Started");

                String messg = ed1.getText().toString();

                for(int i=0; i<messg.length(); i+=10)
                {
                    output[i] = messg.substring(i,i+10);
                    System.out.println(output[i]);
                    count++;

                if (messg == null)
                    output[i] = msg;
                data = output[i].getBytes();
                try
                { //Create packet with target host and target port
                    packet = new DatagramPacket(data,data.length,InetAddress.getByName("192.168.8.17"), 11001);
                    System.out.println("Packet Created");

                } catch (UnknownHostException e) {
                    System.out.println("Exception: Packet Created");

                    e.printStackTrace();
                    Log.e(TAG, e.getMessage());
                }

                try
                {
                    System.out.println("Sending the packet  "+ msg);
                    socket.send(packet);
                    System.out.println("Packet sent");
                } catch (IOException e) {
                    System.out.println("Exception: Packet Send");
                    e.printStackTrace();
                    Log.e(TAG, e.getMessage());
                }
                }
            }     
    }
}
4

0 回答 0