I have this main class:
public class Main {
public static void main(String[] args) {
Server server = new Server(8192);
InetAddress address = null;
try {
address = InetAddress.getByName("192.168.178.249");
} catch (UnknownHostException e) {
e.printStackTrace();
}
int port = 8192;
String s = "het werkt";
byte[] sdata = s.getBytes();
server.send(sdata, address, port);
}
}
And this server class:
public class Server {
private int port;
private Thread listenThread;
private boolean listening = false;
private DatagramSocket socket;
private final int MAX_PACKET_SIZE = 1024;
private final byte[] receivedDataBuffer = new byte[MAX_PACKET_SIZE * 10];
public Server(int port){
this.port = port;
}
public int getPort() {
return port;
}
public void start(){
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
listening = true;
listenThread = new Thread(new Runnable(){
@Override
public void run() {
listen();
}
});
listenThread.start();
}
private void listen() {
while(listening) {
DatagramPacket packet = new DatagramPacket(receivedDataBuffer, MAX_PACKET_SIZE);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
process(packet);
}
}
private void process(DatagramPacket packet){
byte[] data = packet.getData();
System.out.println(new String(data));
}
public void send(byte[] data, InetAddress address, int port){
assert(socket.isConnected());
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
It returns this error:
Exception in thread "main" java.lang.NullPointerException
at com.jakibah.javahacker.Server.send(Server.java:74)
at com.jakibah.javahacker.Main.main(Main.java:22)`
Line 74 is this: } catch (IOException e) {
And Line 22 is this: server.send(sdata, address, port);
Why is it returning this error and how can I fix it? Is it because of the way I send my string?