This is my client code:
package Client;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
public class ClientTest
{
protected DatagramChannel channel;
protected SocketAddress serverAddress;
protected DatagramSocket socket;
protected Selector selector;
protected ByteBuffer packetBuffer;
public static void main(String[] args) throws IOException
{
new ClientTest();
}
public ClientTest() throws IOException
{
serverAddress = new InetSocketAddress("localhost", 4445);
packetBuffer = ByteBuffer.allocate(256);
selector = Selector.open();
channel = DatagramChannel.open();
channel.configureBlocking(false);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
socket = channel.socket();
channel.connect(serverAddress);
packetBuffer.flip();
String packetData = "Test data!";
byte[] pByte = packetData.getBytes();
packetBuffer.rewind();
packetBuffer.put(pByte);
byte[] buf = new byte[packetBuffer.remaining()];
packetBuffer.get(buf);
String s = new String(buf);
System.out.println("Sent: " + s);
channel.write(packetBuffer);
}
}
Server:
package Server;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import Server.ServerTest;
public class ServerTest
{
protected DatagramChannel channel;
protected DatagramSocket socket;
protected Selector selector;
protected ByteBuffer packetBuffer;
protected boolean running;
protected SocketAddress clientAddress;
protected InetSocketAddress iAddress;
public static void main(String[] args) throws IOException
{
new ServerTest();
}
public ServerTest() throws IOException
{
running = true;
packetBuffer = ByteBuffer.allocate(256);
selector = Selector.open();
channel = DatagramChannel.open();
channel.configureBlocking(false);
iAddress = new InetSocketAddress(4445);
channel.bind(iAddress);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
socket = channel.socket();
while(running)
{
if(selector.selectNow() > 0)
{
clientAddress = channel.receive(packetBuffer);
packetBuffer.flip();
byte[] bytes = new byte[packetBuffer.remaining()];
packetBuffer.get(bytes);
String s = new String(bytes);
System.out.println("Client: " + s);
}
}
}
}
The packet gets sent from the client to the server, but it doesn’t seem to send anything but blank spaces, I’m not sure if i’m incorrectly writing information to the buffer, or whether i’m not getting the information from the buffer correctly?
Can someone please give me some insight as to where my code is going wrong?
Signing out, King Chumpanator the great!