I've tried several ways to send a string then an object to my server and have my server doSomething()
then send a string and an object back to the client but as of now the server isn't even receiving the string. below is my current method.
portion of the Server code where send/receive is done:
try
{
ObjectInputStream fromClientObject = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream toClientObject = new ObjectOutputStream(socket.getOutputStream());
while(!socket.isClosed())
{
//If server has received a message
if(fromClientObject.available() > 0)
{
//Set received message to string and print
String input = fromClientObject.readUTF();
System.out.println(input);
//If clients sets .register command then register new user
if (input.equals(".register"))
{
Object obj = fromClientObject.readObject();
Users user = (Users) obj;
server.registerUsers(user);
}
//If clients sends .findUser command then see if user exists in DB
if (input.equals(".findUser"))
{
//Read object from client
Object obj = fromClientObject.readObject();
Users user = (Users) obj;
//Create a pair and find the user
Pair<Boolean,Users> findUsers;
findUsers = server.findUsers(user); //This checks if the user exists and returns true or false
if(findUsers.getFirst())
{
toClientObject.writeUTF("True");
toClientObject.flush();
toClientObject.writeObject(findUsers.getSecond()); //Send the found user object to the client
toClientObject.flush();
}
else
{
toClientObject.writeUTF("false");
toClientObject.flush();
}
}
}
}
}
catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
I've also tried using Scanner
to receive the String and a seperate ObjectInputStream
to receive the object but to no avail.
Below is how the client receives the string and object sent from the server as-well as how it sends information to the server
try(Socket socket = new Socket(host, portNumber);
ObjectInputStream fromServerObject = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream toServerObject = new ObjectOutputStream(socket.getOutputStream()))
{
Thread.sleep(1000);
//Setup I/O
toServerObject.writeUTF(code); //This is the string
toServerObject.flush();
toServerObject.writeObject(user); //This is a serialised object
toServerObject.flush();
if (code.equals(".findUser"))
{
String input = fromServerObject.readUTF();
Users readUser = (Users) fromServerObject.readObject();
if (input.equals("True"))
{
updateMessage("True");
updateValue(readUser);
} else if (input.equals("false"))
{
updateMessage("False");
}
} else
{
updateMessage("True");
}
}
catch (IOException e)
{
System.err.println("Fatal Connection error!");
e.printStackTrace();
updateMessage("Failed");
}
return null;
Any ideas as to how to circumvent this? I was thinking about making separate functions to write a message/receive and a separate to write and receive and object but didn't wan't to attempt it without getting input on my current implementation.