通过互联网的java聊天程序

时间:2013-12-29 07:40:08

标签: java serversocket tcp-ip

好吧,我想要做的基本上是,制作一个可以在互联网上运行的客户端服务器聊天程序,我已经完成了一个基本的,可以在局域网上完美运行,但是无法通过互联网实现它。

服务器:

public class Server extends javax.swing.JFrame {


HashMap<String,PrintWriter> map = new HashMap<String,PrintWriter>();

ArrayList clientOutputStreams = new ArrayList();
ArrayList<String> onlineUsers = new ArrayList();
int port = 5080;
Socket clientSock = null;


public class ClientHandler implements Runnable {

    BufferedReader reader;
    Socket sock;
    PrintWriter client;

    public ClientHandler(Socket clientSocket, PrintWriter user) {
        // new inputStreamReader and then add it to a BufferedReader
        client = user;
        try {
            sock = clientSocket;
            InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
            reader = new BufferedReader(isReader);
            System.out.println("first");
        } // end try
        catch (Exception ex) {
            System.out.println("error beginning StreamReader");
        } // end catch
    } // end ClientHandler()

    @Override
    public void run() {
        System.out.println("run method is running");
        String message;
        String[] data;
        String connect = "Connect";
        String disconnect = "Disconnect";
        String chat = "Chat";


        try {
            while ((message = reader.readLine()) != null) {
                ta1.append(message + "\n");
                ta1.repaint();
                System.out.println("Received: " + message);
                data = message.split("#");
                for (String token : data) {

                    System.out.println(token);

                }


                System.out.println(data[data.length - 1] + " datalast");

                if (data[2].equals(connect)) {

                    tellEveryone((data[0] + "#" + data[1] + "#" + chat));
                    userAdd(data[0]);
                       map.put(data[0], client);

                    } else if (data[2].equals(disconnect)) {
                        System.out.println("barpppppppppp");
                        tellEveryone((data[0] + "#has disconnected." + "#" + chat));
                        userRemove(data[0]);
                        map.remove(data[0]);

                    } else if (data[2].equals(chat)) {

                        tellEveryone(message);

                    } else {
                        System.out.println("No Conditions were met.");
                    }
   } // end while
            } // end try
            catch (Exception ex) {

                System.out.println("lost a connection");
                System.out.println(ex.getMessage());

                clientOutputStreams.remove(client);
            } // end catch
        } // end run()
    }

     public void go() {
 //   clientOutputStreams = new ArrayList();

    try {
        ServerSocket serverSock = new ServerSocket(port);
        System.out.println("ServerSocket Created !");
        System.out.println("Started listening to port " + port);

        while (true) {
            // set up the server writer function and then begin at the same
            // the listener using the Runnable and Thread
            clientSock = serverSock.accept();
            PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
            ta1.append(writer + " ");
             ta1.repaint();
            System.out.println(writer);

            clientOutputStreams.add(writer);
            //data_of_names_and_output_streams.add(writer.toString());


            // use a Runnable to start a 'second main method that will run
            // the listener
            Thread listener = new Thread(new Server.ClientHandler(clientSock, writer));
            listener.start();
            System.out.println("Server Thread for 'new player' was started");
            System.out.println("got a connection");
        } // end while
    } // end try
    catch (Exception ex) {
        System.out.println("error making a connection");
    } // end catch

} // end go()

 public void userAdd(String data) {
    String message;
    String add = "# #Connect", done = "Server# #Done";
    onlineUsers.add(data);
    String[] tempList = new String[(onlineUsers.size())];
    onlineUsers.toArray(tempList);

    for (String token : tempList) {

        message = (token + add);
        tellEveryone(message);
        System.out.println(message);
    }
    tellEveryone(done);
}

public void userRemove(String data) {
    System.out.println(onlineUsers.size() + " is size of online users");
    System.out.println(clientOutputStreams.size() + " is size of ous");
    String message;
    String add = "# #Connect", done = "Server# #Done";
    onlineUsers.remove(data);
    String[] tempList = new String[(onlineUsers.size())];
    onlineUsers.toArray(tempList);

    for (String token : tempList) {

        message = (token + add);
        tellEveryone(message);
    }
    tellEveryone(done);
}

public void tellEveryone(String message) {
     System.out.println(onlineUsers.size() + " is size of online users");
    System.out.println(clientOutputStreams.size() + " is size of ous");
   // jButton1.doClick();
    // sends message to everyone connected to server
    Iterator it = clientOutputStreams.iterator();
    if (message.length() < 250) {
        System.out.println("inside it");

        while (it.hasNext()) {
            try {
                PrintWriter writer = (PrintWriter) it.next();
                writer.println(message);
                //  l1.setText(message);
                System.out.println("Sending " + message);
                writer.flush();
            } // end try
            catch (Exception ex) {
                System.out.println("error telling everyone");
            } // end catch

        }

    } else {
        try {
            clientSock.close();
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

/**
 * Creates new form Server
 */
public Server() {
    initComponents();
   ta1.repaint();
}

 public static void main(String args[]) throws Exception {


    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");


    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Server().setVisible(true);
        }
    });
    new Server().go();
}
} //end form

客户端:jbutton1正在建立连接,jbutton2发送消息。

public class Client extends javax.swing.JFrame {

boolean sent, receive;
SimpleDateFormat sdf;
String ip;
String username;
Socket sock;
BufferedReader reader;
PrintWriter writer;
ArrayList<String> userList = new ArrayList();
Boolean isConnected = false;
DefaultListModel dlm;

 public Client() {
    initComponents();


    dlm = (DefaultListModel) l1.getModel();

    ip = JOptionPane.showInputDialog("Enter the IP of the server to connect");
}

 public class IncomingReader implements Runnable {

    public void run() {
        String stream;
        String[] data;
        String done = "Done", connect = "Connect", disconnect = "Disconnect", chat = "Chat", battlerequest = "battlerequest";

        try {
            while ((stream = reader.readLine()) != null) {

                data = stream.split("#");
                System.out.println(stream + " ------------------------ data");
                if (data[2].equals(chat)) {

                    sdf = new SimpleDateFormat("HH:mm:ss");
                    t.append("(" + sdf.format(new Date()) + ") " + data[0] + ": " + data[1] + "\n");
                    //t.setText("<html><b>hi" + 3 + 3 + "</b></html>");
                } else if (data[2].equals(connect)) {

                    t.removeAll();
                    userAdd(data[0]);

                } else if (data[2].equals(disconnect)) {

                    userRemove(data[0]);

                } else if (data[2].equals(done)) {

                    dlm.removeAllElements();
                    writeUsers();
                    userList.clear();
                } else {
                    System.out.println("no condition met - " + stream);
                }
     }
        } catch (Exception ex) {
            System.out.println(ex.getMessage() + " hi");
        }
    }
}
 public void ListenThread() {
    Thread IncomingReader = new Thread(new Client.IncomingReader());
    IncomingReader.start();
}

public void userAdd(String data) {
    userList.add(data);

}

public void userRemove(String data) {
    t.setText(t1.getText() + data + " has disconnected.\n");
}

public void writeUsers() {
    String[] tempList = new String[(userList.size())];
    userList.toArray(tempList);
    for (String token : tempList) {
        //ul.append( token + "\n");
        dlm.addElement(token);
        // ul.setText(ul.getText() + token + '\n');
    }
}

public void sendDisconnect() {

    String bye = (username + "# #Disconnect");
    try {
        writer.println(bye); // Sends server the disconnect signal.
        writer.flush(); // flushes the buffer
    } catch (Exception e) {
        t.append("Could not send Disconnect message.\n");
    }

}

public void Disconnect() {

    try {
        t.append("Disconnected.\n");
        sock.close();
    } catch (Exception ex) {
        t.append("Failed to disconnect. \n");
    }
    isConnected = false;
    n.setEditable(true);
    dlm.removeAllElements();
    // ul.setText("");

}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    if (isConnected == false && !n.getText().equals("")) {
        username = n.getText();
        n.setEditable(false);

        try {
            sock = new Socket(ip, 5080);
            InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
            reader = new BufferedReader(streamreader);
            writer = new PrintWriter(sock.getOutputStream());
            writer.println(username + "#has connected.#Connect"); // Displays to everyone that user connected.
            writer.flush(); // flushes the buffer
            isConnected = true;
            jLabel4.setText(n.getText());
            //t.append( "<html><font color = \"black\"><b>Server : Welcome,</b></font></html>"+username);
            //t1.setText("<html><font color=\"red\">yo</font></html>");
            // Used to see if the client is connected.
        } catch (Exception ex) {
            t.append("Cannot Connect! Try Again. \n");
            n.setEditable(true);
        }
        ListenThread();
    } else if (isConnected == true) {
        t.append("You are already connected. \n");
    } else if (n.getText().equals("")) {
        t.append("Enter a valid name \n");
    }


}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String nothing = "";
    if ((t1.getText()).equals(nothing)) {
        t1.setText("");
        t1.requestFocus();
    } else {
        try {
            writer.println(username + "#" + t1.getText() + "#" + "Chat");
            writer.flush(); // flushes the buffer
        } catch (Exception ex) {
            t.append("Message was not sent. \n");
        }
        t1.setText("");
        t1.requestFocus();
    }

    t1.setText("");
    t1.requestFocus();       // TODO add your handling code here:
}                                        

private void dicsActionPerformed(java.awt.event.ActionEvent evt) {                                     
    sendDisconnect();
    Disconnect();        // TODO add your handling code here:
}

我还端口转发了我要使用的端口 - 即。 5080

setting up virtual servers

现在,当我的朋友从家里打开客户端程序时,我告诉他输入ip为192.168.1.2,这就是当我打开cmd并键入ipconfig时保存的内容....

setting of network connection

有时我认为我给他的IP地址是错误的coz 192.168.1.2是我猜lan或内部ip地址,所以那么,我也这样做?我在哪里可以获得正确的IP地址?或者我的代码中有其他错误吗?

1 个答案:

答案 0 :(得分:4)

192.168.1.2是不可路由的IP。单击here以获取当前的外部IP(除非您的IP地址是静态的,它可能会定期更改)。

如果您要注册动态DNS服务(例如here),那么您可以给您的朋友一个“域名”(例如something.dnsdynamic.com),当您的IP地址更改。