I have a serious problem with the application i work. I implement a multiplayer mode for a game using NIO. Wher i run the application all look fine but when i install the server in another computer the packets never arrive through network.
How can i fix this problem???
Here is the code:
SERVER
[b]
import java.net.;
import java.io.;
import java.nio.;
import java.nio.channels.;
public class NIOServer {
public final static int DEFAULT_PORT = 3120;
public final static int MAX_PACKET_SIZE = 65507;
public static void main(String[] args) {
int port = DEFAULT_PORT;
try {
DatagramChannel channel = DatagramChannel.open();
DatagramSocket socket = channel.socket();
SocketAddress address = new InetSocketAddress(port);
socket.bind(address);
ByteBuffer buffer = ByteBuffer.allocateDirect(MAX_PACKET_SIZE);
while (true) {
SocketAddress client = channel.receive(buffer);
//data s=buffer.getBytes();
//System.out.print(buffer);
buffer.flip();
channel.send(buffer, client);
buffer.clear();
} // end while
} // end try
catch (IOException ex) {
System.err.println(ex);
} // end catch
} // end main
}[/b]
CLIENT
[b]
import java.net.;
import java.io.;
import java.nio.;
import java.nio.channels.;
import java.util.*;
public class NIOClient{
public final static int DEFAULT_PORT = 3120;
private final static int LIMIT = 1000;
int port = DEFAULT_PORT;
SocketAddress remote;
DatagramChannel channel;
Selector selector;
ByteBuffer buffer;
public NIOClient(){
try{
remote = new InetSocketAddress("localhost", port);
channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.connect(remote);
selector = Selector.open();
channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
buffer = ByteBuffer.allocate(4);
}
catch (IOException ex) {
System.err.println(ex);
}
}
public int channel(int k){
int r=0;
try {
int n = 0;
int numbersRead = 0;
// wait one minute for a connection
selector.select(6000);
Set readyKeys = selector.selectedKeys();
Iterator iterator = readyKeys.iterator();
if (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
if (key.isReadable()) {
buffer.clear();
channel.read(buffer);
buffer.flip();
int echo = buffer.getInt();
System.out.println("Read: " + echo);
numbersRead++;
r=echo;
}
if (key.isWritable()) {
buffer.clear();
buffer.putInt(k);
buffer.flip();
channel.write(buffer);
System.out.println("Wrote: " + k);
n++;
if (n == LIMIT) {
// All packets have been written; switch to read-only mode
key.interestOps(SelectionKey.OP_READ);
}
}
}
} // end try
catch (IOException ex) {
System.err.println(ex);
}
return r;
}
}[/b]