File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Sockets and Internet Protocols and the fly likes How to: synchronize sockets? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "How to: synchronize sockets?" Watch "How to: synchronize sockets?" New topic
Author

How to: synchronize sockets?

Aji Prasetyo
Ranch Hand

Joined: Jun 13, 2007
Posts: 65
Hello,

I am sorry, I have to ask you guys again this time. But please hear me.

Last time I studied about threads synchronization, and I've tried it.
This time, I am coding a network application and I've been trying to "synchronize" it, but no luck so far.

What I mean is: how to make Socket(); which sends something, first waits for ServerSocket() to become available and ready to receive, then actually sends the objects.

below is the sample-code. kind of long, so please bear with me. the server and client side has the same program. Sometimes the console would display this kind of exception:

Java.net.ConnectException: Connection refused: connect
at testproducerconsumer.Drop.put(ProducerConsumerApplet.java:348)
at testproducerconsumer.Producer.run(ProducerConsumerApplet.java:266)


Thank you so much beforehand.

Aji Prasetyo
Ranch Hand

Joined: Jun 13, 2007
Posts: 65
I almost forgot,

Java.net.ConnectException: Connection refused: connect
at testproducerconsumer.Drop.put(ProducerConsumerApplet.java:348)
at testproducerconsumer.Producer.run(ProducerConsumerApplet.java:266)


By the way,
testproducerconsumer.Drop.put(ProducerConsumerApplet.java:348) is this line:
soket = new Socket(AITEPC, PORT);

testproducerconsumer.Producer.run(ProducerConsumerApplet.java:266) is this line:
drop.put(theArray);


Thank you.
Aji Prasetyo
Ranch Hand

Joined: Jun 13, 2007
Posts: 65
Let me rephrase my question,

how to make Socket(); which sends something, first waits for ServerSocket() to become available and ready to receive, then actually sends the objects.


or "How to guarantee that ServerSocket() is ready to receive by the time Socket() is sending in any transfer rate?"

I believe there should be some coding techniques for this matter.

Thank you so much beforehand.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Catch the exception and try again is all that comes to mind. Did you write the server side, too? Any idea why it's not accepting connections?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
/**
* Aji, try: ServerSocketChannel.java
*
* This seems to be recurrent, I believe:
*
* Windows, I/O is not interruptable. I/O and Streams 15 Friday, April 20, 2007 Nicholas Jordan
*

*
* A selectable channel for stream-oriented listening sockets is necessary
* for a reasonably efficient solution, you are using a socket from java.net
* which may be single threaded.
*
* Server-socket channels are not a complete abstraction of listening
* network sockets. Binding and the manipulation of socket options must be
* done through an associated {@link java.net.ServerSocket} object obtained by
* invoking the {@link #socket() socket} method. It is not possible to create
* a channel for an arbitrary, pre-existing server socket, nor is it possible
* to specify the {@link java.net.SocketImpl} object to be used by a server
* socket associated with a server-socket channel.
*
* A server-socket channel is created by invoking the {@link #open() open}
* method of this class. A newly-created server-socket channel is open but not
* yet bound. An attempt to invoke the {@link #accept() accept} method of an
* unbound server-socket channel will cause a {@link NotYetBoundException} to
* be thrown. A server-socket channel can be bound by invoking one of the
* {@link java.net.ServerSocket#bind(java.net.SocketAddress,int) bind} methods
* of an associated server socket.
*
* Server-socket channels are safe for use by multiple concurrent threads.
* ServerSocket.java may not be, in which idea would explain your question.
*/

Another thing I see is doing calcs in a paint method:

  d = getSize();
  xmax = d.width - 1;
  ymax = d.height - 1;
  xcntr = xmax / 2;
  ycntr = ymax / 2;
  g.setColor(Color.BLACK);
  drawLayout(g);
  g.setColor(Color.RED);
  drawPlots(g);

Don't call repaint from run, it does not make good design sense to put it there. What you do is after doing calcs, call a method that informs the OS that you would like to call paint at the next redraw. One would not call paint in this program.

Also, be though it not Saloon coding convention, I would code your Drop::run like this.



Also, you have your //Toggle status. reversed

//Wait until message has been retrieved. is in the wrong place as I see the problem description.

The wait loop is not coded properly by my estimation.

Much of your code concerns its authorship as the writer of the applet, and as Stan James states:  Did you write the server side, too ?

How the server runs has a lot to do with how the client is coded, is this a problem in a student lab where you have the ablilty to write according to what an instructor tells you ?

If not, is it on your own machine ? You can write a server that runs on your own maching, and by writing both sides of the transaction .... gain a much better foothold on the answer to your question.

In general, you would code a server thus:



Looking in the spec's it says:

/**
* Sets the server socket implementation factory for the
* application. The factory can be specified only once.
* <p>
* When an application creates a new server socket, the socket
* implementation factory's <code>createSocketImpl</code> method is
* called to create the actual socket implementation.
* <p>
* Passing <code>null</code> to the method is a no-op unless the factory
* was already set.
*/

It is very convouted to dig the logic out of OO coding practices. You just have a knotty problem, you must be willing to stay with it for us to help you.

Yes: ... guarantee that server is ready to receive by the time Socket() is sending.
And: ...... believe there should be some coding techniques for this matter.

What I do is just keep reading and writing code, much of it seems to come to understanding before long time running.

[ September 21, 2007: Message edited by: Nicholas Jordan ]
[ September 22, 2007: Message edited by: Nicholas Jordan ]

"The differential equations that describe dynamic interactions of power generators are similar to that of the gravitational interplay among celestial bodies, which is chaotic in nature."
Aji Prasetyo
Ranch Hand

Joined: Jun 13, 2007
Posts: 65
Thank you guys for your reply.

The server side code is exactly the same code as the one I already included last time. the different is only at the

the server side code is "true".

Thanks for the advice regarding where to call repaint() method. I have change it into


thanks for the code, but I don't want to send request to the server. you see the program I am coding is always sends packet to the other side (server to client and then client to server) periodically.

I think I am gonna try to catch the exception and try to send again. by the way, what kind of exception should I expecting for this matter?

Thank you so much.
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
Originally posted by Aji Tanaka:
Thank you guys for your reply.


No problem, that's what we're here for.

[Aji Tanaka:]The server side code is exactly the same code as the one I already included last time. the different is only at the ...(lost quote in pasting) ...


That simplifies working the issue enormously, just make the booean source/sink | client/server | producer/consumer (or whatever it is you wish to test) a boolean that is set in the constructor. In simplified form, your immediate coding challenges would be more effectively analyzed by what is called the Model/View/Controller approach. There are many staunch supporters of that approach here, and until one of them speaks up, I suggest moving all of your calcs and data into the data model ~ make all your paint and it's descendent forms a call into the data model that gets a precomputed array, or any other data container you may use, where all the   g.drawRect(xcntr - 5, ycntr - 5, 10, 10);   and g.drawRect(xcntr - 5, ycntr - 5, 10, 10); and g.drawOval((theArray[i][0] / 6) + xcntr, (theArray[i][1] / 6) + ycntr, 1, 1);are already done. You stay on top of what's where by using a controller class. I suggest this is where you put your main() ---> that is what worked for me.

With your calculations and data in the same class, you could put calculations in a run() method, taking some sort of wait() or sleep() to make the screen run at a visible update rate. This would have to be a loop to work, and would be run using a thread constructor for that class, but the calcs should run independently of the screen redraw.

Because you have the sources for both sides, you can run both sides in one process, using two threads -- it will make the machine run much better and is useful because you can experiment and examine changes of approach and changes of coding method, as well as thought models such as Model, View Controller || Producer, consumer || Back of envelope scrawling very effectively and rapidly. One problem solution tool called "Full-Tilt-Boogie" says to have a record player running while you work on the code.

{ }


[Aji Tanaka:]Thanks for the advice regarding where to call repaint() method. I have change it into SwingUtilities.invokeLater

Swing should have an overloaded draw line that takes a Pair of Points or something, these are easy to write, given a Base Class that does something useful, you just update an array of points or Rectangles or something, like this:



I commented out the get (accessor method) because I could not get it to compile. There are a great number of OO proponents here who could get the public Line getLine to work. The code provided here would solve the fixed array bounds problem by making the base class a Vector instead of using an array to hold the points and lines.

Have you run into that yet ?

Put repaints at the end of recalculation, probably doing it the way you cite. What that will allow is convoluted to explain, diecy to work out and just let that invoke later thing do it.

ji Tanaka:] .... I don't want to send request to the server. you see the program I am coding is always sends packet to the other side (server to client and then client to server) periodically.


Just put them in the same call from main, done twice: Once with a boolean true, the next call with the boolean false. Interprocess communication is not the way to go to get one of these things going. Threads can represent each end of the pipe, or channel or Socket Reguest or what ever you model it as in your Program Concept. Just call what you want the client or server to do from a method called run(), then do:

from main(), it will look screwy the first time you run it - and may even hang, but that is a million miles away from trying to develop on a server that is miles away and owned by someone else. Read about servlets, we have a forum here at the Ranch devoted to Servlets. There is a book by Marty Hall that is really really good, but remember to put synchronized anywhere you can in your development code: The compiler will remove any synchronized objects and so on that are not needed. For this level and type of prototyping ... it is often better not to synchronize the access to the data objects because all that happens is that you can see the machine running as it draws the screen, very useful in prototyping.

[Aji Tanaka::]I think I am gonna try to catch the exception and try to send again. by the way, what kind of exception should I expecting for this matter?

Do not program by exceptions, use them to recover from exceptions:

try{y = x / 0;}catchDivideByZeroException{y = 0;}

Here, exection continues after setting y to some sane value. Maybe it should be Float.POSITIVE_INFINITY or +1 or something. Just figure it out. Write your own exception class, as I did. Check with an if(condition) before entry and bailout in an else if things are not in a fixable scope.



[ Message edit by Nicholas Jordan: I have been thinking about this all week - you can use a static synchronized method to simulate a data transmission line. There is some tricky boolean logic to evaluate, but send/receive client/server source/sink evaluation would be greatly simplified by a static synchronized method.]
[ September 29, 2007: Message edited by: Nicholas Jordan ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to: synchronize sockets?