I have set up a UDP client/server model that can send string messages to each other.
I’ve created a custom class LoginRequest which is serialized and sent to the server containing the username and password. When the getters for these variables are called they return null values even though I check the variables before the LoginRequest is sent.
Here is the code for serializing and sending datagram from the client:
private void login(String name, char[] pass) throws SQLException {
try {
LoginRequest login = new LoginRequest(name, pass);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(login);
byte[] buffer= baos.toByteArray();
oos.close();
baos.close();
DatagramPacket packet =
new DatagramPacket(buffer, buffer.length, InetAddress.getByName(SERVER), 10110);
DatagramSocket sSocket = new DatagramSocket();
sSocket.send(packet);
login.getUsername();
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the code for de-serializing the LoginRequest and reading the username:
private void readMessage() {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(cPacket.getData());
ObjectInputStream ois = new ObjectInputStream(bais);
Object obj = ois.readObject();
bais.close();
ois.close();
if(obj instanceof LoginRequest) {
System.out.println("Login request");
LoginRequest login = (LoginRequest) obj;
login.getUsername();
} else {
System.out.println("Not a login request");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the Code for the LoginRequest:
public class LoginRequest implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1379800611469143228L;
private static String username;
private static char[] password;
public LoginRequest(String name, char[] pass) {
username = name;
password = pass;
}
public String getUsername() {
System.out.println("Username: " + username);
return username;
}
public char[] getPassword() {
String p = password.toString();
System.out.println("Password: " + p);
return password;
}
}
When I attempt to read the username or password after this deserialization, I get a NullPointerException. I will be extremely happy if someone can point me in the right direction.
Drop the
staticon your attribute usename and password!