Server/Client Applet Questions

I have two questions.

  1. I have seen many examples of server/client network application but none that involve the client being an applet. Is it possible to have the client be run from an applet on a web page? If so how is this done and how is it different from a normal client.
  2. I would like to start by hosting a server from my home computer, which will run a simple game from an applet on a website hosted from another service provider. The thing I do not understand is that in every example I have seen the HOST is shown to be a “localhost” what must I change this too to let the client run from another computer?

Im sorry if these are confusing questions. Any example code or website links would be appreciated. If anyone wants me to clarify or provide any other information please let me know.

Thanks in advance.

  1. I’m not very familiar with applets. It is Java code running in an applet, so yes, you can connect a socket and do whatever you want. I’m just not sure about applet security.

  2. You can use DynDNS:
    https://www.dyndns.com/
    Sign up then go to My Hosts and create a host. This will give you a domain like somegame.dnsalias.com that you set in DynDNS to point to your external IP. This way you can run your server, etc on your own box and use somegame.dnsalias.com in your game.

For questions 2, the reason I was looking into hosting from home was so that I would not have to signup through any other program or service. Is there a way to have the client applet connect strait to the server running on the home computer?

If the client applet is hosted on the same web/application server as where your java server application is then you can connect to it using Sockets with no security issues (using your IP address instead of Localhost). If you want to host your client applet on a different server to your home computer then connecting with sockets will throw an security expection (as the applet doesnt originate from the host)… I think you can overcome this by signing the applet (but never done this so not sure, don’t like this approach as the client would have to approve security popups on their applets).

Yes. This is what I proposed.

well, if your happy wiht UDP, then here is a great tutorial by Corv, http://corvstudios.com/tutorials/udpMultiplayer.php

also, I agree that dyndns RULES!! I havent even had to mess around with stuff on their site for weeks :slight_smile:

Thanks for all your input I will look into all of this information.

Hey guys I am trying out “dyndns” like you said and I created an account and a host with the name lucreenliven.game-host.org.

Now I am unsure what to do next. Here are sample codes of a server and a client for a simple chat program from “Killer Java Game Programming” and I wanted to know what I need to do to get the server to run on my comp and have any other computer load the client and be able to go on?

Any help would be great.

Thanks in advance.

Note: These are just the to top levels of the codes, if you want all of the files let me know.


///////////////////////////////////////CLIENT///////////////////////////////////////////////////////////////////
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;


public class ChatClient extends JFrame implements ActionListener
{
  private static final int PORT = 1234;     // server details
  private static final String HOST = "lucreenliven.game-host.org";//"localhost";

  private Socket sock;
  private PrintWriter out;  // output to the server

  private JTextArea jtaMesgs;  // output text area
  private JTextField jtfMsg;   // for sending messages
  private JButton jbWho;       // for sending a "who" message


  public ChatClient()
  {
     super("Chat Client");
     initializeGUI();
     // makeContact();

     addWindowListener( new WindowAdapter() {
       public void windowClosing(WindowEvent e)
       { closeLink(); }
     });

     setSize(300,450);
     setVisible(true);

     makeContact();    // change: moved so window visible before contact
  } // end of ChatClient();


  private void initializeGUI()
  /* Text area in center, and controls below.
     Controls:
         - textfield for entering messages
         - a "Who" button
  */
  {
    Container c = getContentPane();
    c.setLayout( new BorderLayout() );

    jtaMesgs = new JTextArea(7, 7);
    jtaMesgs.setEditable(false);
    JScrollPane jsp = new JScrollPane( jtaMesgs);
    c.add( jsp, "Center");

    JLabel jlMsg = new JLabel("Message: ");
    jtfMsg = new JTextField(15);
    jtfMsg.addActionListener(this);    // pressing enter triggers sending of name/score

    jbWho = new JButton("Who");
    jbWho.addActionListener(this);

    JPanel p1 = new JPanel( new FlowLayout() );
    p1.add(jlMsg); p1.add(jtfMsg);

    JPanel p2 = new JPanel( new FlowLayout() );
    p2.add(jbWho);

    JPanel p = new JPanel();
    p.setLayout( new BoxLayout(p, BoxLayout.Y_AXIS));
    p.add(p1); p.add(p2);

    c.add(p, "South");

  }  // end of initializeGUI()


  private void closeLink()
  {
    try {
      out.println("bye");    // tell server that client is disconnecting
      sock.close();
    }
    catch(Exception e)
    {  System.out.println( e );  }

    System.exit( 0 );
  } // end of closeLink()


  private void makeContact()
  // contact the server and start a ChatWatcher thread
  {
    try {
      sock = new Socket(HOST, PORT);
      BufferedReader in  = new BufferedReader(
		  		new InputStreamReader( sock.getInputStream() ) );
      out = new PrintWriter( sock.getOutputStream(), true );  // autoflush

      new ChatWatcher(this, in).start();    // start watching for server msgs
    }
    catch(Exception e)
    {  System.out.println(e);  }
  }  // end of makeContact()



   public void actionPerformed(ActionEvent e)
   /* Either a message is to be sent or the "Who"
      button has been pressed. */
   {
     if (e.getSource() == jbWho)
       out.println("who");   // the response is read by ChatWatcher
     else if (e.getSource() == jtfMsg)
       sendMessage();
   }


  private void sendMessage()
  /* Check if the user has supplied a message, then
     send it to the server. */
  {
    String msg = jtfMsg.getText().trim();
    // System.out.println("'"+msg+"'");

    if (msg.equals(""))
      JOptionPane.showMessageDialog( null,
           "No message entered", "Send Message Error",
			JOptionPane.ERROR_MESSAGE);
    else {
      out.println(msg);
      // showMsg("Sent: " + msg + "\n");
    }
  }  // end of sendMessage()


/*
  synchronized public void showMsgFoo(String msg)
  // Synchronized since this method can be called by this
  //   object and the URLChatWatcher thread.
  {  jtaMesgs.append(msg);  }
*/


  public void showMsg(final String msg)
  /* We're updating the messages text area, so the code should
     be carried out by Swing's event dispatching thread, which is
     achieved by calling invokeLater().

     msg must be final to be used inside the inner class for Runnable.

     showMsg() may be called by this object and the ChatWatcher
     thread, but the updates are serialised by being placed in the
     queue associated with the event dispatcher. This means that
     there's no need to synchronize this method.

     Thanks to Rachel Struthers (rmstruthers@mn.rr.com)
  */
  {
    // System.out.println("showMsg(): " + msg);
    Runnable updateMsgsText = new Runnable() {
      public void run()
      { jtaMesgs.append(msg);  // append message to text area
        jtaMesgs.setCaretPosition( jtaMesgs.getText().length() );
            // move insertion point to the end of the text
      }
    };
    SwingUtilities.invokeLater( updateMsgsText );
  } // end of showMsg()


  // ------------------------------------

  public static void main(String args[])
  {  new ChatClient();  }

} // end of ChatClient class

/////////////////////////////////////SERVER////////////////////////////////////////////////////////////////////////////////////

import java.net.*;
import java.io.*;


public class ChatServer
{
  static final int PORT = 1234;  // port for this server

  private ChatGroup cg;


  public ChatServer()
  // wait for a client connection, spawn a thread, repeat
  {
    cg = new ChatGroup();
    try {
      ServerSocket serverSock = new ServerSocket(PORT);
      Socket clientSock;

      while (true) {
        System.out.println("Waiting for a client...");
        clientSock = serverSock.accept();
        new ChatServerHandler(clientSock, cg).start();
      }
    }
    catch(Exception e)
    {  System.out.println(e);  }
  }  // end of ChatServer()


  // -----------------------------------

  public static void main(String args[])
  {  new ChatServer();  }

} // end of ChatServer class



Please use the “code” tags when posting code.

I don’t understand. Run the server on one computer and run the client on another (or the same) computer. Are you asking how to run a Java program in general?

Ok ill use a code tag next time. Sorry

I want to be able to run the server on my computer and let anyone else who has the client code to be able to run it on his or her computer and connect to the server. Right now I am using “localhost” which mean I can only run the client on my computer, I signed up with dyndns.com but I don’t know how to change my code to make it run with dyndns.com and enable any computer to use the client code.

would be nice if you editted in the code tags, but oh well :P.

anyways, what you are looking for is port forwarding. It is an option in your router. Just forward anything on say port 3333 to your server ip address(lan). And then just replace localhost with lucreenliven.game-host.org.

hope I could help :),
h3ckboy

P.S: if you need anyone outside your lan to test then just post here.

The client code you posted connects to “lucreenliven.game-host.org”. If this is what you setup with DynDNS, this will resolve to your external IP. Next, as h3ckboy mentioned, you need to make port 1234 open to the internet so that clients can connect. Check any software and hardware firewalls you may have and configure them to open the 1234 TCP port.

You can test DynDNS, at a command line run “ping lucreenliven.game-host.org”. If it reports your IP address, it works. You can find your external IP address here (which I find pretty damned funny ;)):
http://moanmyip.com/

If you are going to run a server from home, realize your IP address could change. When this happens DynDNS will be pointing to the wrong place. I run a program every few hours that updates DynDNS with whatever my current IP address is. The program I use is “DNSerSvc”, but you can Google for “DynDNS updater”. Some routers can also update a dynamic DNS service. I don’t actually run a game server, I just like to be able to remote into my home machines. I also run it on friends and families computers, so I can take them over with VNC and fix the computers when they mess them up. :-\

a more efficient way (but less prefered by dyndns). Is just to go to the dynamic dns section on your router. You can just send you IP address without installing any software :).

some points :

1 - you may have trouble to make it working for Applet running on other computer and for applet running locally at the same time, if you want both to work you have to modify your local host table to something like :

lucreenliven.game-host.org 127.0.0.1

this way external user will resolve lucreenliven.game-host.org to your public Internet IP adresse and when you will run the applet locally it will resolve lucreenliven.game-host.org with 127.0.0.1

2 - if you are connecting to internet using a router (probably the case) you must redirect external acces to the TCP port you use to your local computer IP so that when someone connect to your public internet IP using the TCP port XXXX it will be redirected to your computer local network IP using the port XXXX

NB.: probably not the case but if you are connecting to internet using a proxy the server will probably not work cause the proxy wont let your computer act as a server (it wont redirect external connection to your computer)

3 - to enable the applet to connect to the server it must be run from it, this mean that you must have an HTTP server where external user can launch the applet from, like http://lucreenliven.game-host.org/myapplet.html must be working and must return a web page containing the applet

So I have been trying for days to get a sever running on my home computer but despite this wonderful help I have been getting I cannot get it to work. I have a complicated internet connection with many routers and switched in place and I cannot figure it out.

So as an alternative I think I’m going to break down and get a Virtual Private Server (VPS). Can anyone give me some information on what I will need to know to run this server?

The program I will be using is http://www.virtualservernode.com/bronze-node.html.

I under stand there is much more to it than hosting a regular WebPages from a service provider but I don’t know what to expect, I am still fairly new to the Webmaster world and have little formal training on the matter.

Any information would be helpful, and if I’m getting in way over my head please let me know. I am willing to learn any system or program to make this work.

Thanks in advance.

Not exactly sure what you’re after, but Google’s AppEngine gives you 10 free app deployments based on servlets.
Works good but has high (300ms) latency.

Well I’m going to get my own “server” so I’m assuming I will need software, and a cpanel and other things. I’m wondering how hard this is to do with limited knowledge of servers in general.

I’m looking for information and maybe a tutorial on how to set up a server and what software I will need.

Forget about server hardware and basic server software. You need a VPS (virtual private server)
which can be rented very cheaply, and will come running a complete suite of everything you need
except your own software. Most VPS are linux, but windows versions also exist. If you have no
familiarity with unix, quite a bit of head-banging can be expected if you try to use a unix based
machine. Either way, you won’t need to worry much about the standard server software, only
setting up your application in that environment.

I plan to get a VPS from http://www.virtualservernode.com/bronze-node.html

Now what do I need to know and do to go from this to having WebPages run on the server and having them accessed on the net?

Don’t rush to rent a server. There’s no reason to do so until
you have a fully functional web site running at home.
Assuming your usual development environment is windows, load windows version of the tools you use on your development machine, develop, and and
test locally.

The VPS ought to be already running apache, perl, mysql and
lots of other common unix tools. Thenjust uploa d copies of fully
debugged programs and web pages.

You’ve obviously got a lot to learn. You can probably find some
very useful tutorials. Have fun.