I've very new to JAVA and socket programming and I'm developing a distributed system of clients, servers and notification systems for a Uni assignment. There are a total of 3 processes running for this program, each with multiple threads. The notification systems generate notifications, sends them to the server which then distributes them to clients.
When a new client connects to the server I need them to pull down all notifications for services they have subscribed to. To do this I am sending three serialised JSON Object fetch requests (one for each notification severity) to the server through a socket. The server always receives the first two of these JSON objects but almost never the third.
Code for client sending fetch requests:
out = new PrintWriter(sd.getSocket().getOutputStream(), true);
// First send a fetch for all severities
for (Severity severity : Severity.values()){
JSONObject fetchRequest = new JSONObject();
fetchRequest.put("sType",utils.config.MessageType.FETCH.toString());
fetchRequest.put("sSeverity",severity.toString());
fetchRequest.put("lSentTS",System.currentTimeMillis());
sd.getSocketLock().lock();
//System.out.println(fetchRequest.toString());
out.println(fetchRequest.toString());
sd.getSocketLock().unlock();
}
Code for server receiving JSON object:
while (true) {
JSONObject newMessage = utils.socket.getJSONObject(socket);
String messageType = (String) newMessage.get("sType");
boolean isContinue = true;
// Determine message type and handle
switch (utils.config.MessageType.valueOf(messageType)){
case SERVICE:
isContinue = handleServiceMessage(newMessage);
break;
case NOTIFICATION:
isContinue = handleNotification(newMessage);
break;
case FETCH:
isContinue = handleFetchRequest(newMessage);
break;
default:
System.err.println(idServiceStr + "Invalid messageType '" + newMessage.get("sType") + "'");
System.err.println(idServiceStr + "Continuing to listen...");
}
If I sleep the client thread between sending JSON objects then it works. I have also tested with only one thread running in each of the client and server processes.
Whats going on here? The sockets should be running over tcp so nothing should get dropped and I would of thought I would get an exception if the socket buffer overflowed and dropped one.
Edit:
Each client will have a thread for sending data down the socket and a thread for listening. Both sit below a thread that initialises them. sd stands for sharedData and is an object that contains the socket, a lock and a few other things that shouldn't be relevant to the problem.
MessageType is an enum.
Code for getJSONObject
static public JSONObject getJSONObject(Socket socket) throws IOException, JSONException{
InputStream in = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream inBuf = new ByteArrayOutputStream();
int result;
while((result = bis.read()) != -1 && result != (byte)'\r') {
inBuf.write((byte) result);
}
return new JSONObject(inBuf.toString());
}