1

I am writing the server side of an UDP Socket in Processing and encountering a NullPointerException every time on the line DatagramPacket receivePacket = new DatagramPacket(receiveData, 4096);. The client side is a Python file. Here is the code for the server. The methods setup() and draw() are called through different Processing files.

import processing.net.*;
import java.io.*;
import java.net.*;
import java.util.*;

//Server myServer;
DatagramSocket serverSocket;
byte[] receiveData;
InetAddress IPAddressList;
int portList = -1;

void setup(){
  try{
      DatagramSocket serverSocket = new DatagramSocket(21567);
  }
  catch (IOException e){
    e.printStackTrace();
    System.out.println(e);
  }

   byte[] receiveData = new byte[4096];
}

void draw(){

  float P1,P2,P3;
  print ("hello");
  try{
     DatagramPacket receivePacket = new DatagramPacket(receiveData, 4096);
     serverSocket.receive(receivePacket);
     String greeting = new String(receivePacket.getData());
     System.out.println("From Client: " + greeting);
     IPAddressList = receivePacket.getAddress();
     portList= receivePacket.getPort();
     P1 = Integer.valueOf(greeting);
     print(P1);
     print (greeting);
   }
   catch (IOException e){
    System.out.println(e.getMessage());
  }

  for (int i=0;i<receiveData.length;i++){
    print(receiveData[i]);
  }
}
Nayuki
  • 17,911
  • 6
  • 53
  • 80
dawnoflife
  • 1,572
  • 10
  • 42
  • 62

1 Answers1

5

The line where you pointed out the NullPointerException is very helpful.

The problem is that you initialized a local variable receiveData instead of the field receiveData in the outer scope.

To solution is to simply replace the line byte[] receiveData = new byte[4096]; with receiveData = new byte[4096];.

In general, this is called name shadowing:

Nayuki
  • 17,911
  • 6
  • 53
  • 80
  • After editing the code like you said, I get the `NullPointerException` on the next line now...`serverSocket.receive(receivePacket);` – dawnoflife Aug 26 '11 at 04:43
  • 1
    Ah. Same problem with the variable `serverSocket`: don't declare it locally. – Nayuki Aug 26 '11 at 04:45
  • To reiterate explicitly, what you did is that within the `try` block you created the variables `serverSocket` and `receiveData`, which are **different** from the same-named variables `serverSocket` and `receiveData` created further above in the outer scope. This effect is called name shadowing. – Nayuki Aug 26 '11 at 04:46