开发者

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);
     serverSocke开发者_如何学Got.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]);
  }
}


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:

  • http://en.wikipedia.org/wiki/Variable_shadowing
  • http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.3.1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜