Reputation: 33
So I am currently working on a client application that listens on port 5004 for RTP packets. Since there may be multiple servers sending RTP packets, I can't use sockets to connect to a specific remote host. Instead, I have tried the following to listen on a local port:
Socket socket = new Socket("127.0.0.1", 5004);
Socket socket = new Socket("localhost", 5004);
Socket socket = new Socket(InetAddress.getByName("localhost"), 5004);
Socket socket = new Socket(InetAddress.getLocalHost(), 5004);
Any of the above will give me this exception:
java.net.ConnectException: Connection refused: connect
I have also tried using a DatagramSocket, but DatagramPackets require that I specify the size of the packet to be read.
To summarize, I need to find a way to listen on local port 5004 for RTP packets of unknown size without connecting to a specific remote host/address. Any help is greatly appreciated!
EDIT:
I now have a ServerSocket set up to listen for connections, but I still can't manage to read in any packets.
try { ServerSocket server = new ServerSocket(5004);
Socket s = server.accept();
BufferedReader rtpReader = new BufferedReader(new InputStreamReader(s.getInputStream()));
while (true){
int k = rtpReader.read();
if (k == -1) break;
System.out.println(k);
}
}
Note: The RTP packets are sent over a Multicast address.
The problem turned out to be the Multicast. Refer to Nikolai's answer. Thanks alot!
Upvotes: 3
Views: 4872
Reputation: 84239
You have to use java.net.MulticastSocket
, and join the multicast group. Something like:
// put your multicast address here
InetAddress group = InetAddress.getByName( "244.10.10.10" );
MulticastSocket sock = new MulticastSocket( 5004 );
sock.joinGroup( group );
byte[] buf = new byte[1472];
DatagramPacket pack = new DatagramPacket( buf, buf.length );
while ( whatever ) {
sock.receive( pack );
// handle data
}
sock.leaveGroup( group );
Upvotes: 2
Reputation: 10493
You need to create a new ServerSocket class, and then use the accept() method to use the Socket created when someone connects to your listening server/ port.
ServerSocket server = new ServerSocket(5004);
Socket s = server.accept();
// You can now use the socket "s"...
Upvotes: 2