Hey everyone,
I am working on the networking for an app and have built a static Networking class that sends messages to our server.
My static method, aptly named send() sends a string that is decoded on the server and processed.
Network.send(string);
However many components use this static method to send messages to the server, so to avoid any clashes I synchronized the Network.send(string) method.
So its all working fine, one component at a time sends a message to the server, la la la!
But I was talking to a colleague and she said that if I create a new Socket each time I call the static method I don't have to synchronize the send method, and it will save time as each component won't have to wait for others to finish. She also said it won't cause any adverse effects to the networking, such as binding exceptions.
So we got together and both tested our Network classes and they both work. However I have a feeling the my colleagues approach will cause some kind of error or dependency on the Socket.close() function.
My code has a single static Socket that is shared, here's an exmaple of what the code looks like.
private static Socket soc;
public static synchronized void send()
{
soc = new Socket(ip, port);
soc.write(); // Send stuff to the server
soc.read(); // Get reply from the server
soc.close(); // Close the Socket
}
My colleague's code looks like the following:
public static void send()
{
Socket soc = new Socket(ip, port); // Create a new socket each time send() is called
soc.write(); // Send stuff to the server
soc.read(); // Get reply from the server
soc.close(); // Close the Socket
}
So whats are the pro's and con's of each approach?
In my opinion, my synchronized approach may be a tad slower but is the safer way but I may be wrong. Anyone have any thoughts? My reputation is on the line here!
Edited by: Jaxie on Sep 9, 2009 6:45 AM
Edited by: Jaxie on Sep 9, 2009 6:52 AM