I am doing some testing with SCTP in a simple client server model.
My Server code is following:
public class SCTPServer extends Thread {
InetSocketAddress serverSocketAddress=null;
SctpServerChannel sctpServerChannel;
SctpChannel sctpChannel;
boolean running = false;
ByteBuffer bf = ByteBuffer.allocateDirect(160);
String id= null;
public SCTPClient sctpClient= null;
public SCTPServer(String IP, int port, String clientIp, int clientPort, String id) {
try {
serverSocketAddress = new InetSocketAddress(IP, port);
sctpServerChannel = SctpServerChannel.open().bind(serverSocketAddress);
} catch (Exception e) {
System.out.println("Failed to open Sctp connection Reciver on IP:" + IP + " and Port:" + port+" "+e);
System.exit(0);
}
}
public void run()
{
running = true;
while (running) {
try {
sctpClient.sendAsp();
sctpChannel = sctpServerChannel.accept();
try {
sctpChannel.receive(bf, null, null);
bf.flip();
byte[] barry = new byte[bf.limit()]; //we may keep the received data on this new byte arrray here or in some
bf.get(barry, 0, bf.limit());
bf.clear();
System.out.println("new sctp message is received");
System.out.println(new String(barry));
} catch (IOException ex) {
System.out.println("Failed to receive from sctp Channel " + ex);
}
} catch (Exception ex) {
System.out.println("Exception at Starting SCTP Server channel"+ ex);
}
}
}
}
and the client code following:
public class SCTPClient extends Thread {
SctpChannel sctpChannel;
InetSocketAddress socketAddress;//= new InetSocketAddress("202.51.176.44", 5555);
boolean runniung = false;
ByteBuffer bf = ByteBuffer.allocateDirect(160);
String id= null;
public SCTPClient(String ip, int port, int maxInStream, int maxOutStream, String id) {
socketAddress = new InetSocketAddress(ip, port);
this.id = id;
//InetSocketAddress sockAd = new InetSocketAddress("202.51.176.44",55556);
try {
sctpChannel = SctpChannel.open();
System.out.println("SCTP connection opened with IP==" + ip + " port == " + port);
//sctpChannel.bind(sockAd);
sctpChannel.connect(socketAddress, maxInStream, maxOutStream);
runniung = true;
sendMSG();
} catch (Exception ex) {
System.out.println("Exception at opening sctp connection:" + ex);
System.exit(0);
}
}
public void sendMSG()
{
MessageInfo messageInfo =null;
/*try {
} catch (IOException ex) {
System.out.println("Failed to create Message Info " + ex.toString());
}*/
messageInfo = MessageInfo.createOutgoing( null, 0);
ByteBuffer byteBuffer = buildMessage(1, "test");
try {
sctpChannel.send(byteBuffer, messageInfo);
byteBuffer.clear();
System.out.println("A message has been sent");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Failed to send the message due to :" + e.toString());
}
}
public static ByteBuffer buildMessage(Integer id,String infoString)
{
//We can calculate the total length of the message hard codedly, even before building the total message.
int totalLength = (id!=null) ? 16 : 8;
totalLength += (infoString!=null) ? (4+infoString.length()) : 0;
ByteBuffer data = ByteBuffer.allocateDirect(totalLength);
//Own part of ASP Up message
if(id!=null)
{
data.putInt(ASPIdentifier);
}
if(infoString!=null)
{
data.put(infoString.getBytes());
}
return data;
}
}
The problem here is that, when I try to connect to a remote PC the SCTP association is established successfully. But when the SendMSG function is called the system aborts with following exception
java.net.SocketException: Invalid argument
at sun.nio.ch.SctpChannelImpl.send0(Native Method) Failed to send the message due to :java.net.SocketException: Invalid argument
at sun.nio.ch.SctpChannelImpl.sendFromNativeBuffer(SctpChannelImpl.java:1027)
at sun.nio.ch.SctpChannelImpl.send(SctpChannelImpl.java:987)
at sun.nio.ch.SctpChannelImpl.send(SctpChannelImpl.java:967)
at sctptester.SCTPClient.sendMSG(SCTPClient.java:79)
at sctptester.SCTPClient.<init>(SCTPClient.java:40)
at test.main(test.java:66)
After comparing your client code to a simulator that I just wrote last week, I can see only one real difference. You did not bind your client's socket to a local InetSocketAddress. Where you have:
sctpChannel.bind(sockAd);
You need to put something like:
InetSocketAddress localISA = new InetSocketAddress(localIPAddress, localPort);
sctpChannel.bind(localISA);
I believe this will do it for you, or at least get you past the error you posted.
I think you should add the destination when sending in the client,
messageInfo = MessageInfo.createOutgoing( null, 0);
//replace with
msgInfo = MessageInfo.createOutgoing(new InetSocketAddress(ip, port), 0);
Related
I want to chat on two or more device using wifi without internet. I am sending message using socket from first android mobile to second mobile. I have faced issue that some massage is received and some massage skip and not received on second mobile. I have tried Multicastsoket and Datagramsoket but text message skipped. following is my send side and receiver side code.
**- Sender side**
public static void sender(final String ipAddress, final String message) {
// Creates the thread for capturing and transmitting audio
/* AsyncTaskExample asyncTask = new AsyncTaskExample();
asyncTask.execute(message);*/
Thread replyThread = new Thread(new Runnable() {
#Override
public void run() {
try {
InetAddress address = InetAddress.getByName(ipAddress);
byte[] data = message.getBytes();
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(data, data.length, address, BROADCAST_PORT);
socket.setReuseAddress(true);
socket.send(packet);
Log.i(LOG_TAG, "Sent message( " + message + " ) to " + ipAddress);
socket.disconnect();
socket.close();
} catch (UnknownHostException e) {
Log.e(LOG_TAG, "Failure. UnknownHostException in sendMessage: " + ipAddress);
} catch (SocketException e) {
Log.e(LOG_TAG, "Failure. SocketException in sendMessage: " + e);
} catch (IOException e) {
Log.e(LOG_TAG, "Failure. IOException in sendMessage: " + e);
}
}
});
replyThread.start();
}
**- Receiver side**
public void receiver() {
// Creates the thread for receiving massage
Thread receiveThread = new Thread(new Runnable() {
#Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(BROADCAST_PORT);
// InetAddress group = InetAddress.getByName(myIPAddress);
//socket.setSoTimeout(1000);
byte[] buffer = new byte[BUF_SIZE];
DatagramPacket packet = new DatagramPacket(buffer, BUF_SIZE);
while (LISTEN) {
// Listen for incoming call requests
try {
Log.i(LOG_TAG, "Listening for incoming message");
/* Arrays.fill(buffer,(byte)0);*/
socket.receive(packet);
String data = new String(buffer, 0, packet.getLength());
Log.i("SocketMSG", "Packet received from " + packet.getAddress() + " with contents: " + data);
String action = data.substring(0, 4);
//Toast.makeText(context,"Packet received from",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
socket.disconnect();
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
});
receiveThread.start();
}
You could implement TCP-like behavior on top of UDP, see this repo for example: https://github.com/jin-zhe/reliable-UDP/blob/master/Sender.java
I made a Chat Application (Server/Client) using Java. Note: The server is ran as its own jar file and each client is ran as its own jar file.
Each client is on their own thread.
Whenever I send messages to the server, each client receives the message, however when I send messages from the client, only the server receives the message. When the client sends a message, I want all connected clients and the server to receive the message so all of the clients can communicate together and with the server as well.
I've looked at multiple posts and videos about this, but most were too confusing for me to understand.
Could someone please help me understand how I can send messages between threads? Thanks!
-- My Code --
Client:
public Client(User user, String address, int port) {
try {
socket = new Socket(address, port);
ClientApplicationUI app = new ClientApplicationUI();
app.setTitle("Chat Application - " + user.getUsername());
app.setVisible(true);
ServerConnection connection = new ServerConnection(socket, app);
output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
new Thread(connection).start();
app.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (app.getTextField().getText() != null && app.getTextField().getText().length() > 0) {
String message = MessageUtil.getMessage(Message.LOGGER_PREFIX) + " <" + user.getUsername() + "> " + app.getTextField().getText() + "\n";
try {
output.writeUTF(message);
output.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
} catch (UnknownHostException e) {
System.out.println(e);
System.out.println("Could not connect! Reason: " + e);
} catch (IOException e) {
System.out.println("Could not connect! Reason: " + e);
}
}
ServerConnection
public class ServerConnection implements Runnable {
#SuppressWarnings("unused")
private Socket socket;
private DataInputStream in;
private ClientApplicationUI app;
public ServerConnection(Socket socket, ClientApplicationUI app) throws IOException {
this.socket = socket;
this.app = app;
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
#Override
public void run() {
while (true) {
String message;
try {
message = in.readUTF();
app.logMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Server
public class Server {
private Socket socket = null;
private ServerSocket server = null;
private ExecutorService pool = Executors.newFixedThreadPool(4);
public Server (int port) {
try {
ApplicationUI app = new ApplicationUI();
app.setVisible(true);
server = new ServerSocket(port);
app.logMessage(MessageUtil.getMessage(Message.LOGGER_PREFIX) + " " + MessageUtil.getMessage(Message.INFO) + " Server started!\n");
app.logMessage(MessageUtil.getMessage(Message.LOGGER_PREFIX) + " " + MessageUtil.getMessage(Message.INFO) + " Waiting for new connections...\n");
while (true) {
socket = server.accept();
ConnectionHandler clientThread = new ConnectionHandler(socket, app);
app.logMessage(MessageUtil.getMessage(Message.LOGGER_PREFIX) + " " + MessageUtil.getMessage(Message.INFO) + " A new client has been accepted!\n");
pool.execute(clientThread);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server(58139);
}
}
ConnectionHandler
public class ConnectionHandler implements Runnable {
private Socket client;
private ApplicationUI app;
private DataInputStream in;
private DataOutputStream out;
public ConnectionHandler(Socket client, ApplicationUI app) throws IOException {
this.client = client;
this.app = app;
in = new DataInputStream(new BufferedInputStream(client.getInputStream()));
out = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
}
#Override
public void run() {
try {
app.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (app.getTextField().getText() != null && app.getTextField().getText().length() > 0) {
String message = MessageUtil.getMessage(Message.LOGGER_PREFIX) + " <Server> " + app.getTextField().getText() + "\n";
try {
sendMessage(message);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
String message = "";
while (!message.equals("/stop")) {
message = in.readUTF();
app.logMessage(message);
}
} catch (IOException e) {
System.err.println("IO exception in connection handler!");
System.err.println(e.getStackTrace());
} finally {
try {
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendMessage(String message) throws IOException {
out.writeUTF(message);
out.flush();
}
}
You need to understand, how sockets work. They are always Client and Server.
There are two ways you could achieve what you want:
First solution:
Send the message which is meant for all clients to the server and let the server distribute the message to all the other clients. The server will need to keep track of the already connected clients, i.e. store their Socket.
Second solution: (which totally is not advisable)
If you want to send a message to a client of a network without haveing the actual server involved, you will need that client to act as a server, or the other way around. This means that every client will actually need to listen to every other client, instead of only the server.
You should definitely go with the first solution!
I need a Java Proxy Server that let me connect to [localhost:9318] through [localhost:9418], like:
[my browser] -> [localhost:9418] -> [localhost:9318]
for that I tried this code:
http://www.java2s.com/Code/Java/Network-Protocol/Asimpleproxyserver.htm
package com.example.proxyserver;
import java.io.*;
import java.net.*;
public class App {
public static void main(String[] args) throws IOException {
try {
String host = "localhost";
int remoteport = 9318;
int localport = 9418;
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport + " on port " + localport);
// And start running the server
runServer(host, remoteport, localport); // never returns
} catch (Exception e) {
System.err.println(e);
}
}
/**
* runs a single-threaded proxy server on the specified local port. It never
* returns.
*/
public static void runServer(String host, int remoteport, int localport) throws IOException {
// Create a ServerSocket to listen for connections with
ServerSocket ss = new ServerSocket(localport);
final byte[] request = new byte[1024];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
// Wait for a connection on the local port
client = ss.accept();
final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
// Make a connection to the real server.
// If we cannot connect to the server, send an error to the
// client, disconnect, and continue waiting for connections.
try {
server = new Socket(host, remoteport);
} catch (IOException e) {
PrintWriter out = new PrintWriter(streamToClient);
out.print("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n");
out.flush();
client.close();
continue;
}
// Get server streams.
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();
// a thread to read the client's requests and pass them
// to the server. A separate thread for asynchronous.
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
// Start the client-to-server request thread running
t.start();
// Read the server's responses
// and pass them back to the client.
int bytesRead;
try {
while ((bytesRead = streamFromServer.read(reply)) != -1) {
streamToClient.write(reply, 0, bytesRead);
streamToClient.flush();
}
} catch (IOException e) {
}
// The server closed its connection to us, so we close our
// connection to our client.
streamToClient.close();
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
}
catch (IOException e) {
}
}
}
}
}
This code works but it is very slow.
Do you know what do I need to do in order to increase the speed?
Or maybe do you know about another Java Proxy Server code that be fast?
Thanks!
Hi Stackover flow world,
Thought I'd send something over as I haven't shared a question in some time. I've been pretty stumped on the weirdest, possibly simplest question ever, that I've been finding all sorts of different responses online.
Basically, I have a SimpleServer which looks as so:
// A generic server that listens on a port and connects to any clients it
// finds. Made to extend Thread, so that an application can have multiple
// server threads servicing several ports, if necessary.
public class SimpleServer
{
protected int portNo = 8082; // Port to listen to for clients
protected ServerSocket clientConnect;
public SimpleServer(int port) throws IllegalArgumentException {
if (port <= 0)
throw new IllegalArgumentException(
"Bad port number given to SimpleServer constructor.");
// Try making a ServerSocket to the given port
System.out.println("Connecting server socket to port...");
try { clientConnect = new ServerSocket(port); }
catch (IOException e) {
System.out.println("Failed to connect to port " + port);
System.exit(1);
}
// Made the connection, so set the local port number
this.portNo = port;
}
public static void main(String argv[]) {
int port = 8088;
if (argv.length > 0) {
int tmp = port;
try {
tmp = Integer.parseInt(argv[0]);
}
catch (NumberFormatException e) {}
port = tmp;
}
SimpleServer server = new SimpleServer(port);
System.out.println("SimpleServer running on port " + port + "...");
server.listen();
}
public void listen() {
// Listen to port for client connection requests.
try {
System.out.println("Waiting for clients...");
while (true) {
Socket clientReq = clientConnect.accept();
System.out.println("Got a client...");
serviceClient(clientReq);
}
}
catch (IOException e) {
System.out.println("IO exception while listening for clients.");
System.exit(1);
}
}
public void serviceClient(Socket clientConn) {
SimpleCmdInputStream inStream = null;
DataOutputStream outStream = null;
try {
inStream = new SimpleCmdInputStream(clientConn.getInputStream());
outStream = new DataOutputStream(clientConn.getOutputStream());
}
catch (IOException e) {
System.out.println("SimpleServer: Error getting I/O streams.");
}
SimpleCmd cmd = null;
System.out.println("Attempting to read commands...");
while (cmd == null || !(cmd instanceof DoneCmd)) {
try { cmd = inStream.readCommand(); }
catch (IOException e) {
System.out.println("SimpleServer: " + e);
System.exit(1);
}
if (cmd != null) {
String result = cmd.Do();
try { outStream.writeBytes(result); }
catch (IOException e) {
System.out.println("SimpleServer: " + e);
System.exit(1);
}
}
}
}
public synchronized void end() {
System.out.println("Shutting down SimpleServer running on port "
+ portNo);
}
}
Then I have a SimpleClient which looks as so:
public class SimpleClient
{
// Our socket connection to the server
protected Socket serverConn;
// The input command stream from the server
protected SimpleCmdInputStream inStream;
public SimpleClient(String host, int port)
throws IllegalArgumentException {
try {
System.out.println("Trying to connect to " + host + " " + port);
serverConn = new Socket(host, port);
}
catch (UnknownHostException e) {
throw new IllegalArgumentException("Bad host name given.");
}
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
System.out.println("Made server connection.");
}
public static void main(String argv[]) {
if (argv.length < 2) {
System.out.println("Usage: java SimpleClient [host] [port]");
System.exit(1);
}
System.out.println("Getting here");
String host = argv[0];
int port=0;
try {
port = Integer.parseInt(argv[1]);
}
catch (NumberFormatException e) {}
SimpleClient client = new SimpleClient(host, port);
System.out.println("Commands are about to send?");
client.sendCommands();
}
public void sendCommands() {
try {
OutputStreamWriter wout =
new OutputStreamWriter(serverConn.getOutputStream());
BufferedReader rin = new BufferedReader(
new InputStreamReader(serverConn.getInputStream()));
wout.write("what is a man is a good man\n");
wout.flush();
rin.readLine();
System.out.println("getting here yo");
// Send a GET command...
wout.write("GET goodies ");
// ...and receive the results
String result = rin.readLine();
System.out.println(result + "I am here");
System.out.println("Server says: \"" + result + "\"");
// Now try a POST command
wout.write("POST goodies ");
// ...and receive the results
result = rin.readLine();
System.out.println("Server says: \"" + result + "\"");
// All done, tell the server so
wout.write("DONE ");
result = rin.readLine();
System.out.println("Server says: \"" + result + "\"");
}
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
}
public synchronized void end() {
System.out.println("Closing down SimpleClient...");
try { serverConn.close(); }
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
}
}
Connected to the target VM, address: '127.0.0.1:64335', transport: 'socket'
Getting here
Trying to connect to localhost 8088
Made server connection.
Commands are about to send?
Output
Connected to the target VM, address: '127.0.0.1:64335', transport: 'socket'
Getting here
Trying to connect to localhost 8088
Made server connection.
Commands are about to send?
For some reason the client freezes at 'commands are about to send', and for some reason doesn't truly 'write' to the socket when sending these commands to the server.
Any clues, am i missing something, completely off the mark here?
Thanks!
Arsalan
Figured it out, seems like there's so much drama when it comes to all the types of streams, writers, readers, etc. It seems that somehow my samples have used the types of these streams incorrectly, as the clear difference to understand is that streams are for everything that implement Output or Input Stream, and are for essentially for reading or writing binary data.
Readers & writers are a layer above streams for reading and writing text. Readers and writers convert binary data from and to characters using a character encoding.
Basically now do this in my SimpleClient
public class SimpleClient
{
// Our socket connection to the server
protected Socket serverConn;
// The input command stream from the server
protected SimpleCmdInputStream inStream;
public SimpleClient(String host, int port)
throws IllegalArgumentException {
try {
System.out.println("Trying to connect to " + host + " " + port);
serverConn = new Socket(host, port);
}
catch (UnknownHostException e) {
throw new IllegalArgumentException("Bad host name given.");
}
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
System.out.println("Made server connection.");
}
public static void main(String argv[]) {
if (argv.length < 2) {
System.out.println("Usage: java SimpleClient [host] [port]");
System.exit(1);
}
System.out.println("Getting here");
String host = argv[0];
int port=0;
try {
port = Integer.parseInt(argv[1]);
}
catch (NumberFormatException e) {}
SimpleClient client = new SimpleClient(host, port);
client.sendCommands();
}
public void sendCommands() {
try {
DataOutputStream wout =
new DataOutputStream(serverConn.getOutputStream());
DataInputStream rin = new DataInputStream(serverConn.getInputStream());
// Send a GET command...
wout.writeChars("GET goodies ");
// ...and receive the results
String result = rin.readLine();
System.out.println("Server says: \"" + result + "\"");
// Now try a POST command
wout.writeChars("POST goodies ");
// ...and receive the results
result = rin.readLine();
System.out.println("Server says: \"" + result + "\"");
// All done, tell the server so
wout.writeChars("DONE ");
result = rin.readLine();
System.out.println("Server says: \"" + result + "\"");
}
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
}
public synchronized void end() {
System.out.println("Closing down SimpleClient...");
try { serverConn.close(); }
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
}
}
Notice the new type of the output and input streams, rather than writers.
Thanks Arsalan!
I have written an app which receives multicast packets sent by a sender (containing audio).
I have used Netty 4 and have got the app working on Windows but it will not receive multicast packets when run on Linux (Debian Wheezy (raspi) and Ubuntu 12).
I have created some test code that can send and receive multicast packets, the results are:
Send Windows to Windows works.
Send Linux to Windows works.
Send Windows to Linux, packets are sent but not received.
I run the app as root and have SO_BROADCAST set to true.
What have I missed?
If I use the standard Java MulticastSocket instead of Netty, then the app works, but I would prefer to use Netty as it is easy to use and simplifies to code greatly.
The test code is :
public class TestMulticast {
private int port = 51972;
private Logger log = Logger.getLogger(this.getClass());
private InetAddress remoteInetAddr = null;
private InetSocketAddress remoteInetSocket = null;
private InetAddress localInetAddr = null;
private InetSocketAddress localInetSocket = null;
private DatagramChannel ch = null;
private EventLoopGroup group = new NioEventLoopGroup();
private boolean bSend = false;
public TestMulticast(String localAddress, String remoteAddress, String sPort, boolean bSend) {
this.bSend = bSend;
try {
localInetAddr = InetAddress.getByName(localAddress.trim());
remoteInetAddr = InetAddress.getByName(remoteAddress.trim());
} catch (Exception e) {
log.error("Error creating InetAddresses. Local: " + localAddress + " Remote: " + remoteAddress, e);
}
try {
port = Integer.parseInt(sPort);
} catch (Exception e) {
log.error("Error Parsing Port: " + sPort, e);
}
}
public void run() throws Exception {
log.debug("Run TestMulticast, Send Packet = " + bSend);
try {
localInetSocket = new InetSocketAddress(port);
remoteInetSocket = new InetSocketAddress(remoteInetAddr, port);
Bootstrap b = new Bootstrap();
b.group(group);
b.channelFactory(new ChannelFactory<Channel>() {
#Override
public Channel newChannel() {
return new NioDatagramChannel(InternetProtocolFamily.IPv4);
}
});
b.option(ChannelOption.SO_BROADCAST, true);
b.option(ChannelOption.SO_REUSEADDR, true);
b.option(ChannelOption.IP_MULTICAST_LOOP_DISABLED, false);
b.option(ChannelOption.SO_RCVBUF, 2048);
b.option(ChannelOption.IP_MULTICAST_TTL, 255);
b.handler(new LoggingHandler(LogLevel.DEBUG));
log.debug("Am I Logged on as ROOT: " + PlatformDependent.isRoot());
ch = (DatagramChannel) b.bind(localInetSocket).sync().channel();
log.debug("Result of BIND: " + ch.toString());
if (remoteInetAddr.isMulticastAddress()) {
NetworkInterface nic = NetworkInterface.getByInetAddress(localInetAddr);
ChannelFuture future = ch.joinGroup(remoteInetSocket, nic);
log.debug("Result of Join: " + future.toString());
} else {
log.debug("############NOT A MULTICAST ADDRESS: '" + remoteInetAddr.getHostAddress() + "'");
}
if (bSend) {
group.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
try {
Date date = new Date();
byte[] bytes = date.toString().getBytes();
ByteBuf buffer = Unpooled.copiedBuffer(bytes);
DatagramPacket packet = new DatagramPacket(buffer, remoteInetSocket, localInetSocket);
ch.writeAndFlush(packet);
} catch (Exception e) {
log.error("Error Sending DatagramPacket", e);
}
}
}, 0, 10, TimeUnit.SECONDS);
}
} catch (Exception e) {
log.error(e);
}
}
public void stop() {
try {
if (ch != null) {
try {
ch.close();
} catch (Exception e) {
log.error("Error Closing Channel", e);
}
}
group.shutdownGracefully();
} catch (Exception e) {
log.error("Error ShuutingDown", e);
}
}
}
EDIT:
If found my problem, I should learn to read the docs!!
For Mutlicast you should bind to the WILDCARD Address.
So changing the code to
localInetSocket = new InetSocketAddress(remotePort);
....
ch = (DatagramChannel) b.bind(localInetSocket).sync().channel();
....
if (remoteInetAddr.isMulticastAddress()) {
NetworkInterface nic = NetworkInterface.getByInetAddress(localInetAddr);
ChannelFuture future = ch.joinGroup(remoteInetSocket, nic);
log.debug("Result of Join: " + future.toString());
}
I've modified the full code above with the new changes..
Pete.