Вопрос

I am trying to connect to a socket using this code

public static Socket connectToSocket(String name)
    {
        try
        {
            while(true)
            {
                byte[] receiveData = new byte[name.length()];
                DatagramSocket clientSocket = new DatagramSocket(PORT);
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                clientSocket.receive(receivePacket);

                if(Arrays.equals(name.getBytes(),receiveData))
                {
                    return new Socket(receivePacket.getAddress(),PORT);
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

But my problem is i dot know what size to make my byte array for all information to be processed. I tried just making the receiveData array an enormous size, but i realized that wouldnt work because it would mess up this statement.

        if(Arrays.equals(name.getBytes(),receiveData))

What would be the best way to deal with this issue.

Это было полезно?

Решение

The DatagramPacket contains the length of the data actually received. See the 'length()' method.

But I'm curious about this protocol. Why not just connect to the server with TCP and ask it its name? and eliminate the UDP part altogether?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top