wood burning stoves*
The moose likes Beginning Java and the fly likes Listening for connections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Listening for connections" Watch "Listening for connections" New topic
Author

Listening for connections

Moin Phillips
Greenhorn

Joined: Jan 23, 2007
Posts: 4
Hi,

I'm new to these forums and came across it through the Head First books. Anyway, Im creating a simple chat program and I've coded all the client side files, placed them in a jar and signed them. This part works perfectly fine on my local machine and and from a remote server (at the moment only shows the GUI of the chat room).

I'm having trouble with the next bit, that is how do I listen for connections 24/7?

I know that I need some form of loop that listens for connections, btw I'm using sockets and I know all about them and I have even coded a few parts to this. So, if I have a clas file with a main method that continuously listens for connections, how do i get it to run on a server 24/7?

I'd prefer to stay away from Servlets and JSP as i am still readin the Head First book on that, but I know you can do it through Jar files cant you?
Chris Beckey
Ranch Hand

Joined: Jun 09, 2006
Posts: 116

java.net.ServerSocket may be what you are looking for
Moin Phillips
Greenhorn

Joined: Jan 23, 2007
Posts: 4
Yes, I know about the ServerSockets, but what I'm trying to say is how do you run a main method on a server? Do servers have command lines from where you can run a server.java file and let it run continuously?
Chris Beckey
Ranch Hand

Joined: Jun 09, 2006
Posts: 116

Here is I think basically what you want ...
1.) from main, create an instance of a service thread
2.) the service thread opens the server socket and waits for client connections
3.) the main thread just waits for "administrative" input
4.) spawn off, or grab a thread from a pool to service requests from within the service thread

The code below is basically it, but take it with a grain of salt as I wrote it in about 5 minutes. It will keep running as long as nothing is available on System.in.

Chris Beckey
Ranch Hand

Joined: Jun 09, 2006
Posts: 116

start it with "java Server" from a command line.
If you want to run it as a service (on Windows) Google for "java windows service", there are a number of apps that will help there.
Moin Phillips
Greenhorn

Joined: Jan 23, 2007
Posts: 4
Thanks for the code, but I've already got most of that done.

I'm not talking about running a service on windows, I'm talking about an actual Web Server (something you can buy commercially, the thing that this forum is running on). How do I get my Server.java file running on there, where there is no Windows?

Plus whats the deal with these damn applets? I've made mine into JAR files and signed them and done pretty much everything by the book and I still get SocketPermission errors! There are no files being accessed nothing being changed, only messages sent forth and back. I dont want to mess around with policy files as my chatroom will have hundreds of clients and I dont want to be giving them directions to changing their policy files.

Thank you for you help so far.

Mo
Chris Beckey
Ranch Hand

Joined: Jun 09, 2006
Posts: 116

>>I'm not talking about running a service on windows, I'm talking about an actual Web Server (something you can buy commercially, the thing that this forum is running on). How do I get my Server.java file running on there, where there is no Windows?

Well that does change things rather significantly and unfortunately complicates things also.

What platform (web server, servlet container, application server, etc...) do you have in mind (Apache, Tomcat, JBoss, WebSphere, IIS, ...)? Is it something you have control over or are you stuck with what an ISP provides?

==========
The rest of this reply is sorta' random stuff until the above question is answered.

The first question is why? it doesn't look like you are using what a web server provides you (i.e. HTTP protocol support) so why do you want to run on one? Also, can a chat application be adequately implemented given the limitations of HTTP (i.e. request/response pattern)?

Speaking rather generally, web servers don't provide for their hosted applications to be starting service sockets because that is what the web server does. It is at least theoretically possible to write a connector (for Tomcat) that would do what you want but that is forcing a square peg into a round hole. For other web/app servers I don't know. You might try looking for "startup" classes in the documentation.
What app/web server do you have in mind to run on? and again do you really have to? Could you run a standalone chat server on the same box as the web server?

Another question, would you expect the clients to receive un-initiated messages? that is, not a response to a request that the applet made?

Here is a link to an article on tunneling RMI over HTTP: http://java.sun.com/developer/technicalArticles/RMI/rmi/
Moin Phillips
Greenhorn

Joined: Jan 23, 2007
Posts: 4
The only reason I want to use a web server is to make my chatroom live, i.e. make it available to clients on the Internet. I would stick with the free webspace from Geocities if that worked!

I been researching a lot about this and think these problems are due to my lack of knowledge of servers. I designed my chatroom on a client-server model, I have completed the client side and the server side only works on my local machine. The problem now arises when I try to make my chatroom 'public' or live on the Internet.

There are so many technologies flying around, I've tried to experiment with PHP and PostGres and Java itself has so many solutions JSP/Servlets, RMI, Web Start which all sound confusing to me at the moment.

Therefore i decided on just putting the class files in a JAR and on a server and hope they work without having a container like apache or tomcat or anything, btw I'm using my University's server at the moment which has java installed on it. Once this project is complete I plan on getting a commercial one.

The client side works but when connecting to the server I get socketpermission errors.

Basically, do you think that I'am going about this the right way or do you think I should use some other technology?
Aaron Shaw
Greenhorn

Joined: Jan 19, 2007
Posts: 9
I think i know what you mean, Moin. I run a java MUD, which is a text based game where many players can connect.

I have the main game loop run like this:


while(shutdown == false) {

blah blah blah....

Thread.sleep(50);

}


The game runs in this loop forever, until the boolean 'shutdown' is set to true by an admin. The thread.sleep(50) makes the thread pause for 50 miliseconds each loop, in an attempt to stop the program from locking up completely any other programs i need to run.


Whether this is good practise or not, im not sure. Anyone feel free to provide a more elegant solution.

[ January 23, 2007: Message edited by: Aaron Shaw ]


The part that listens for incoming connections runs in another thread, but the loop is the same, and the thread is lower priority.

You dont need a web server. You're not serving up html. Just run you program on whatever port you like, such as 6666, and connect using telnet or any custom client you made, etc.
[ January 23, 2007: Message edited by: Aaron Shaw ]
Chris Beckey
Ranch Hand

Joined: Jun 09, 2006
Posts: 116

This response may be a bit pedantic, but will hopefully clear up the issue.

Web Server 101 ... with vague generalities that will probably get me flamed.<g>

A web server, in its most elemental form, simply listens for and responds to HTTP requests. Basically that means it gets an HTTP request (a string in a specified form), determines what resource (think HTML file) the request is for and sends the content of the resource (file) back to the requestor, formatted as an HTTP response. That is basically all a web server does. Other than the specific of parsing/assembling the HTTP requests/responses and locating resources, (involved and initially trivial, respectively) the code I posted earler, and that you have written, is the core of a web server.
So a web server is an application that understands HTTP protocol. Fine ... call 'em "HTTP servers", its more accurate, more precise and avoids HTML involvement that the server doesn't really care about.

In your case you have an HTML file that contains an applet tag. The HTML file is one resource, the applet is another. All the web server does is respond to requests for those resources (from a browser) and return the bytes that make up the page and the applet. Effectively this allows you to download code to the client. The client (the browser) then runs that code because it knows that it Java byte code (the response includes type information). In this example, the browser is far more sophisticated than the server.

All fine up to now, you have gotten code loaded on a client and it is running. Now the applet wants to communicate with a server. Assuming it is going to be through a socket, the first question is what protocol? That is, what is the client going to send to the server and what is the server going to respond with? Also, what is the messaging pattern? Will the client always initiate a request, followed by a server response? Can the server send an unsolicited message to the client?
==>Draw boxes for the client(s) and servers, connect them with lines and then determine what goes from the client to the server, to the other client, etc ... Then think about the perspective of each box (i.e. server waits for messages and responds, client sends message and waits for response, etc ...)

The applet is not restricted to HTTP or any other defined protocol, it can send whatever it wants down the wire. BUT, it is restricted to talking to only the server it was loaded from, that is a function of Java sandbox security (and maybe why you are getting the exception, see references below).

Once you answer all that stuff about messaging pattern and content then you can determine if HTTP is a valid choice for the protocol and if it is then you may be able to use a web server as your chat server. Read on ...
=> The short answer is that it will work but not particularly well, which implies that a web server is not the optimal solution. The bit about drawing boxes and the perspective of each box should illustrate why.

Now to slightly more complex stuff. In HTTP the requested resource does not have to be a static file. For example a request for an HTML page with the the current time must change constantly. That is where active server content in one form or another comes in, that may be servlet/JSP, PHP, Ruby, ASP, ASP.net, CGI, ISAPI DLL, etc. But basically the interface is the same, that is:
Request - the name of the resource and possibly some parameters
Result - the resource contents as a stream of bytes (with some type information)
Note that the fact that the protocol is HTTP has not changed. The browser knows nothing about how the content is generated, it just gets back a stream of bytes and either displays it or executes it (again depending on type, which is part of the response).
If active content on an HTTP server is the route you decide to take, then pick a technology and then pick a server that implements it.

==> Summary
You're doing this for the education, right? If not, find an existing IRC server/client implementation and install it.
An HTTP server is probably not the best fit.
The ability to download and run Java code can be addressed with WebStart without the limitations on server communication of an applet.
This problem has already been solved and codified (see below for IRC), implement to that spec, or at least read enough of it to understand the rationale.
Deploying a generic Java (server) application on a hosted system is gonna' be half a step from impossible. If you do have the intention of deploying this commercially, you may have to host it yourself.
Despite all that, it does sound like you are on the right track. The problem may be more complex than originally thought.


References:
HTTP protocol ftp://ftp.isi.edu/in-notes/rfc2616.txt
you don't have to read it from cover to cover, just the basics of request and response format

IRC (chat) protocol http://www.irchelp.org/irchelp/rfc/
this problem has been solved, even if you don't implement the entire spec the basics of the messaging will be the same

Java tutorial on applets/server communication:
http://java.sun.com/docs/books/tutorial/deployment/applet/clientExample.html
... and maybe find your exception answer here.

Run TCP Monitor and watch HTTP browser/server interaction (you must download Axis to get it). This is most illuminating ...
http://ws.apache.org/axis/java/user-guide.html#AppendixUsingTheAxisTCPMonitorTcpmon
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Listening for connections