I have a server application that I want an applet client to connect with. How can the applet determine the address of the originating serverwithout having to hard-code the address in the applet? Also, how can the server application get the address of the connecting applet?
The best way to tell an applet what server it should connect to is to pass the server IP address or hostname and port number as an applet parameter. That way, you have to change only the HTML file if the server changes. If your server is running on the same machine as the Web serverfrom which the applet was downloaded (which is often the case), you can play some tricks with getCodeBase() or getDocumentBase() to discoverthe hostname. Either method will return a URL instance from which you can extract the host by calling getHost(). However, I do not recommend doing this because it limits your ability to test your applet during development. You actually have to load it from a Web server every time. During development, you will probably want to load it from the local file system using appletviewer or a Web browser. When you do this, the code base and document base URLs will not have a host property. An alternative is to use an applet parameter only for testing purposes, and when you actually deploy the applet, switch over to querying the base URL. But if you do this, and you move your server to a host different from your Web server, you will break the applet. Once you know your options and their limitations, you can make the decision most appropriate to your situation.
To answer your second question, the server application can obtain the address of the connecting applet straight from the socket connection. Your server will be listening for incoming connections using a ServerSocket. Accepting a connection with accept() produces aa Socket instance that is used to communicate with the applet. You can get the applet’s host information by calling the Socket’s getInetAddress method.