0

I need a little help with implementation of reading a data from socket in my application.

I'm working on application which is listening for a data using Socket and parsing received data. The problem is that I need to connect to my device and start the socket so I can receive the data. I was using ServerSocket which is blocking and waiting to stop the other socket, which is sending me the data, and parse the data after that. But I need to be able to read the stream before closing the server's socket.

So any idea how can I achieve this kind of implementation and which classes I have to use about that?

4

1 回答 1

0

The following code is what im using to listen broadcast messages from network:

void startBroadcastListener(final int receivingPort)
{
    new Thread() 
    {
        public void run() 
        {
            try 
            {
                int port = receivingPort;
                dsocket = new DatagramSocket(port);
                byte[] buffer = new byte[2048];

                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                while (true) 
                {
                    //System.out.println("Receiving...");
                    dsocket.receive(packet);
                    String msg = new String(buffer, 0, packet.getLength());
                    packet.setLength(buffer.length);


                    String binaryString = convertHexToBinary(packet.getData()).replaceAll("\\s","");

                    //System.out.println(packet.getAddress().getHostName() + ": " + binaryString);
                }
            }
            catch (Exception e) 
            {
                e.printStackTrace();
            }
        }
    }.start();
}
于 2012-07-26T08:18:33.177 回答