我在处理中编写UDP套接字的服务器端,每次在DatagramPacket receivePacket = new DatagramPacket(receiveData, 4096);
行上都遇到NullPointerException。客户端是一个Python文件。这是服务器的代码。通过不同的处理文件调用方法setup()
和draw()
。
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]);
}
}
最佳答案
您指出NullPointerException
的行非常有帮助。
问题是您在外部范围中初始化了局部变量receiveData
而不是字段receiveData
。
解决方案是将byte[] receiveData = new byte[4096];
行替换为receiveData = new byte[4096];
。
通常,这称为名称重影:
关于java - UDP套接字处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7200032/