Question


The application consists of a server and a client. When I run the application locally using the ip (127.0.0.1) the chat works just fine. Of course the whole point in this is to run the messenger on an online server so that I could connect to it from another computer and be full of pride and joy.

My question is (and I know that it sounds like I didn't do any research and I am lazy... believe me I am perplexed) What do I need to do with the program and where can I upload it?

I want to access my program from outide my local network and not just test it on my computer.


the client app:

package helloworldC;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

 public class client extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;


//constructor
public client(String host){
    super("Client");
    serverIP = host;
    userText= new JTextField();
    userText.setEditable(false);
    userText.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent event) {
            sendMessage(event.getActionCommand());
            userText.setText("");

        }
    }
    );
    add(userText, BorderLayout.NORTH);
    chatWindow= new JTextArea();
    add(new JScrollPane(chatWindow), BorderLayout.CENTER);
    setSize(300,150);
    setVisible(true);

}

//connect

public void startRunning(){
    try{
    connectToServer();
    setupStreams();
    whileChatting();
    }catch(EOFException eofException){
    showMessage("\n Client terminated") ;
    }catch(IOException ioException){
        ioException.printStackTrace();
    }
    finally{
        closeCrap();
    }


}
//conect to server

private void connectToServer() throws IOException{
    showMessage("connecting...\n");
    connection = new Socket(InetAddress.getByName(serverIP),6789);//52
    showMessage("Connected to: " + connection.getInetAddress().getHostName());
}
// set up streams 53
private void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\n streams are ready");

}

//while chatting 54 

private void whileChatting() throws IOException{
    ableToType(true);
    do{
        try{
            message = (String) input.readObject();
            showMessage("\n"+message);
        }catch(ClassNotFoundException classNotFoundException){
            showMessage("\n class problen");
        }
    }while(!message.equals("SERVER -END"));

}

//close the streams and sockets
private void closeCrap(){
    showMessage("\n closing sheet");
    ableToType(false);
    try{
        output.close();
        input.close();
        connection.close();
    }catch(IOException ioException){
        ioException.printStackTrace();

    }

}
//send messages 56

private void sendMessage(String message){
    try{
        output.writeObject("CLIENT - "+ message);
        output.flush();
        showMessage("\nCLIENT -"+message);

    }catch(IOException ioException){
        chatWindow.append("\n something is wrong");

    }

}
//update chatWindow57

private void showMessage(final String m){
    SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
            chatWindow.append(m);

        }
    });


}

//permission to type

private void  ableToType(final boolean tof){
    SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
            userText.setEditable(tof);

        }
    });


}

}

the server :

package helloworld;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


 public class Server extends JFrame {
 private JTextField userText;
 private JTextArea chatWindow;
 private ObjectOutputStream output;
 private ObjectInputStream input;
 private ServerSocket server;
 private Socket connection;






//constructor
public Server(){
super("Messenger");
userText=new JTextField();
userText.setEditable(false);
userText.addActionListener(
    new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent event) {
            sendMessage(event.getActionCommand());
            userText.setText("");
        }
    }   
);
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300,150);
setVisible(true);   
}
// set up and run the server
public void startRunning(){
try{
server = new ServerSocket(6789, 100);   
    while(true){
        try{
            //connect and have conversation
            waitForConnection();
            setupStreams();
            whileChatting();

        }catch(EOFException eofException){
            showMessage("\n Server ended the connection! ");
        }finally{
            closeCrap();
        }



    }
}catch(IOException ioException){
    ioException.printStackTrace();
}   
}

//wait for connection, then display connection information
  private void waitForConnection() throws IOException {
showMessage("Waiting for connection...\n");
connection = server.accept();
showMessage("now connected to "+connection.getInetAddress().getHostName()+"\n");
}

//get stream to send and receive data
private void setupStreams() throws IOException {
 output = new ObjectOutputStream(connection.getOutputStream());
 output.flush();
 input = new ObjectInputStream(connection.getInputStream());
 showMessage("\n Streams are good!\n");
 }
 //during the chat conversation
 private void whileChatting() throws IOException{
  String message = " You are now connected! ";
  sendMessage(message);
  ableToType(true);
  do{
      try{
          message = (String) input.readObject();
          showMessage("\n"+message);
      }catch(ClassNotFoundException classNotFoundException){
          showMessage("\n wtf???");
      }
  }while(!message.equals("CLIENT - END"));

}

// close streams and sockets
private void closeCrap(){
  showMessage("\n Closing all...\n");
  ableToType(false);
  try{
      output.close();
      input.close();
      connection.close();
  }catch(IOException ioException){
      ioException.printStackTrace();
  }
}
//send a message to client
 private void sendMessage(String message){
   try{
       output.writeObject("SERVER - "+message);
       output.flush();
       showMessage("\nSERVER - " + message);
   }catch(IOException ioException){
       chatWindow.append("\n ERROR: cant send");
   }
}
private void showMessage(final String text){
   SwingUtilities.invokeLater(
           new Runnable() {
            public void run() {
                chatWindow.append(text);
            }
        }   
   );
 }
 private void ableToType(final boolean tof){
   SwingUtilities.invokeLater(
           new Runnable() {
            public void run() {
                userText.setEditable(tof);
            }
        }   
   );

 }
}

No correct solution

OTHER TIPS

The reason that the IP 127.0.0.1 works is beacause thats the IP of something called localhost. Since you are hosting both the server and the client on the machine that works just fine.

When you want to have lets say the server program on one computer and client on another inside your local network (only accessed from inside of your network) you have to point the IP adress of the client to your server's IP adress.

But things are a bit diffrent when you want to access it from OUTSIDE of your network. Its similar to before, just that you have to port forward your server's IP from your router with the port (6789 in your case). What this does is that when your routers public IP receives data with the port 6789, it knows where to send it. If it doesen't know, it just discards it.

When you have port forwarded your router to accept data from port 6789. You need to find out your public IP adress. (which is farily easy to do, just head to: http://www.whatsmyip.org/) Then from outside your local network, start up your client on a computer. Then replace the IP that the client shall connect with to whatever your public IP is.

NOTE: Your router's public IP adress changes from time to time, so that if you try to connect one day your routers public IP may have changed. A way to avoid this is to use DDNS (dynamic domain name system) but that is another topic.

Hope this helps!
-Kad

At first you will need a server provider that allows you to run java programs. I'm not into which provider is good or bad so you might set up a server yourself at your home (e.g. using http://de.dyn.com/dns/ to provide you with the necessary fixed dns). But remember to keep track of security issues (open ports and other stuff) and that the computer must be online to have the chat accessable which might result in high energy cost. On the other hand you can than use it for a load of other stuff too (e.g. Webserver, FTP and so on).

Looking at it this way your problem is not so java dependent as you just have to replace the ip in your program, i guess ;)

My reading is that you are experimenting with Java and programming and are now curious as to how to deploy an application into the wild. You could try a raw server such as an Amazon Web Service free account; but you will be biting off a lot of setup, net admin, sys admin work. Most service don't provide a graphical interface so using JFrame and swing is not going to work. You will be better off using a free web PaaS such as redhat openshift and making websockets chat app if you want to learn how to make software that runs in the wild.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top