Two threads, one socket
I'm trying to create a communications manager module for my
application which is responsible for the sending and receiving of
messages between nodes in the network using TCP and persistent sockets
(in-order confirmed delivery is a requirement). Each node opens are
ServerSocket immediately to receive messages. Sockets are created the
first time a message is sent to a certain destination and the
PrintWriter is stored in a HashMap to be retrieved the next time a
message is sent to the same node.
The problem occurring frequently is that while one node may send and
receive messages as it should, the other one may miss out on some
messages or not receive any at all (though it can still send messages
which are properly received by the first node). No exceptions are
shown to indicate any problems.
The code for sending messages is as follows (ignore that the loops or
sockets are not terminated):
[code]
public void SendMsg(String destadd, Message myMsg) {
Socket sendsock = null;
PrintWriter printtemp = null;
printtemp = SendingConnectionList.get(destadd);
if(printtemp == null) {
sendsock = ConnectToOpenPort(destadd, sendsock);
if(sendsock != null) {
try {
printtemp = new PrintWriter
(sendsock.getOutputStream(), true);
SendingConnectionList.put(destadd, printtemp);
} catch (IOException ex) {
System.out.println(destadd+" "+ex);
}
}
} else {
//System.out.println("Socket already exists: " + destadd);
}
String msgtosend = myMsg.myMsgType.toString() + "=" +
GlobalVars.myCommMgr.get_my_address() + "=" + myMsg.content;
if(printtemp != null) {
printtemp.println(msgtosend);
}
}
private Socket ConnectToOpenPort(String destadd, Socket sendsock)
{
int trycount = 0;
while(sendsock == null && trycount<3) {
try {
sendsock = new Socket();
sendsock.bind(null);
sendsock.connect(new InetSocketAddress(destadd,
GlobalVars.port), 300);
} catch (UnknownHostException ex) {
System.out.println(ex);
sendsock = null;
trycount++;
} catch (IOException ex) {
System.out.println(ex);
sendsock = null;
trycount++;
}
}
return sendsock;
}
[/code]
I've tried a simpler client/server case where the client sends
messages in two threads and the server receives them properly.
However, when I make this go both ways and add another thread, the
problem reemerges. If anyone would like to try the code, I've uploaded
both cases at this link: [url=http://www.megaupload.com/?d=K4R58YRQ]
http://www.megaupload.com/?d=K4R58YRQ[/url]. Testmulti is the simple
one that works, while Multest is the advanced one that causes
problems.
Any help would be greatly appreciated. Thanks!