我有一个java服务器和客户端聊天程序,但我可以在哪里上传它?

时间:2014-01-24 13:27:14

标签: java sockets client-server chat java-server


该应用程序由服务器和客户端组成。当我使用ip(127.0.0.1)在本地运行应用程序时,聊天工作正常。当然,这一点的重点是在在线服务器上运行信使,以便我可以从另一台计算机连接到它并充满自豪和快乐。

我的问题是(我知道这听起来我没有做过任何研究而且我很懒...相信我,我很困惑)我需要对程序做什么以及我可以在哪里上传它?

我想从我的本地网络访问我的程序而不只是在我的计算机上测试它。

<小时/> 客户端应用程序:

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);

        }
    });


}

}

服务器:

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);
            }
        }   
   );

 }
}

3 个答案:

答案 0 :(得分:2)

IP 127.0.0.1工作的原因是因为这是名为 localhost 的IP。由于您在机器上托管服务器和客户端,工作正常。

如果您想让一台计算机上的服务器程序和本地网络内另一台计算机上的客户端(只能从网络中的 访问),您必须指向客户端的IP地址到您服务器的IP地址。

但是当您想从网络的外部访问它时,情况有点不同。它与以前类似,只是你必须从你的路由器端口转发你的服务器的IP端口(在你的情况下是6789)。这样做是当您的路由器公共IP使用端口6789接收数据时,它知道将其发送到何处。如果它不知道,它就会丢弃它。

当您有端口转发路由器以接受来自端口6789的数据时。您需要找到您的公共IP地址。 (这很容易做到,只需前往:http://www.whatsmyip.org/) 然后从外部您的本地网络,在计算机上启动您的客户端。然后将客户端连接的IP替换为您的公共IP。

注意:您的路由器的公共IP地址会不时更改,因此,如果您尝试连接一天,您的路由器公共IP可能已更改。避免这种情况的一种方法是使用DDNS(动态域名系统),但这是另一个主题。

希望这有帮助!
-Kad

答案 1 :(得分:0)

首先,您需要一个允许您运行Java程序的服务器提供程序。我不知道哪个提供商好或坏,所以你可以自己在家里设置服务器(例如使用http://de.dyn.com/dns/为你提供必要的固定dns)。但请记住要跟踪安全问题(开放端口和其他内容),并且计算机必须在线才能使聊天可访问,这可能会导致高昂的能源成本。另一方面,你可以使用它来加载其他东西(例如Webserver,FTP等)。

以这种方式看待你的问题并非如此依赖于java,因为你只需要替换程序中的ip,我猜;)

答案 2 :(得分:0)

我的阅读是您正在尝试Java和编程,现在对如何将应用程序部署到野外感到好奇。您可以尝试使用原始服务器,例如Amazon Web Service免费帐户;但你会咬掉很多设置,网络管理员,系统管理工作。大多数服务都没有提供图形界面,因此使用JFrame和swing是行不通的。如果你想学习如何制作在野外运行的软件,你最好使用免费的网络PaaS,如redhat openshift和制作websockets chat app