dawnoflife
dawnoflife

Reputation: 1652

UDP Sockets Processing

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]);
  }
}

Upvotes: 1

Views: 1591

Answers (1)

Nayuki
Nayuki

Reputation: 18552

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:

Upvotes: 5

Related Questions