java 简单的文字聊天应用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15729989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:40:25  来源:igfitidea点击:

Simple text chat application

javaapplet

提问by puneetverma0711

I have developed simple text chat application using applets in java. It consists of two files.

我使用 java 中的小程序开发了简单的文本聊天应用程序。它由两个文件组成。

  1. server.java-> to access server part
  2. client.java-> to access client part
  1. server.java-> 访问服务器部分
  2. client.java-> 访问客户端部分

After opening both applet , chat can happen between server & client.

打开两个小程序后,可以在服务器和客户端之间进行聊天。

Here's my server side code:

    Serverfile.java

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

    public class serverfile extends JFrame {
    private JTextField usertext;
    private JTextArea chatwindow;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private ServerSocket server;
    private Socket connection;

    public serverfile(){
    super("server messaging system");    
    usertext= new JTextField();
    usertext.setEditable(false);
    usertext.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent event){
    sendmessage(event.getActionCommand());
    usertext.setText("");
      }
    }
    );
    add(usertext,BorderLayout.SOUTH);
    chatwindow= new JTextArea();
    add(new JScrollPane(chatwindow));
    setSize(300,250);
    setVisible(true);
    }

   public void startrunning(){
   try{
   server= new ServerSocket(6789,100);
   while(true){
   try{
   waitForConnection();
   setupstream();
   whilechatting();
   }catch(Exception e){
   System.out.println("you have an error in coversation with client");
   }finally{
   closecrap();
   }
   }
   }
   catch(Exception e){
   System.out.println("you have an error in connecting with client");
   }
   }
   private void waitForConnection() throws IOException{

   showmessage("waiting for someone to connect");
   connection= server.accept();
   showmessage("now connected to"+connection.getInetAddress().getHostName());
   }

   private void setupstream() throws IOException{

   output= new ObjectOutputStream(connection.getOutputStream());
   output.flush();
   input= new ObjectInputStream(connection.getInputStream());
   showmessage("\n streams are setup");
   }

   private void whilechatting()throws IOException{

   String message = "\n you are now connected";
   sendmessage(message);
   ableToType(true);
   do{
   try{
   message = (String)input.readObject();
   showmessage("\n"+message);
   catch(Exception e){
   System.out.println("\n error in reading message");
   }
   }while(!message.equals("CLIENT-END"));
   }

   private void closecrap(){

   showmessage("\nclosing connection");
   ableToType(false);
   try{
   output.close();
   input.close();
   connection.close();
   }catch(Exception e){
   System.out.println("\n error in closing server");

   }
   }

   private void sendmessage(String message){

   try{
   output.writeObject("SERVER-"+message);
   output.flush();
   }catch(Exception e){
   chatwindow.append("\n error in sending message from server side");
   }
   }

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


    Server.java-> which access serverfile code:

    import javax.swing.JFrame

     public class server {
      public static void main(String args[]){
      serverfile obj1= new serverfile();
      obj1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     obj1.startrunning();
         }    
           }

My client side code:

我的客户端代码:

    Clientfile.java

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

        public class clientfile extends JFrame {
          private JTextField usertext;
          private JTextArea chatwindow;
          private ObjectOutputStream output;
           private ObjectInputStream input;
          private String message="";
            private String serverIP;
            private ServerSocket server;
               private Socket connection;

             public clientfile(String host){
              super("client messaging system");  
             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.SOUTH);
 chatwindow= new JTextArea();
 add(new JScrollPane(chatwindow));
 setSize(300,250);
 setVisible(true);
}

        public void startrunning(){
            try{
       connecttoserver();
         setupstream();
          whilechatting();
        }catch(Exception e){
         System.out.println("you have an error in coversation with server");
            }
           finally{
           closecrap();
               }
               }
            private void connecttoserver() throws IOException{
          showmessage("attempting connection");
          connection= new Socket(InetAddress.getByName(serverIP),6789);
         showmessage("connected to"+connection.getInetAddress().getHostName());
           }
             private void setupstream() throws IOException{
             output= new ObjectOutputStream(connection.getOutputStream());
          output.flush();
            input= new ObjectInputStream(connection.getInputStream());
        showmessage("\n streams are good to go");
              }

          private void whilechatting()throws IOException{
         ableToType(true);
            do{
           try{
           message = (String)input.readObject();
             showmessage("\n"+message);
        }catch(Exception e){
          System.out.println("\n error in writing message");
            }
        }while(!message.equals("SERVER - END"));
             }

        private void closecrap(){
       showmessage("\nclosing....");
         ableToType(false);
              try{
        output.close();
        input.close();
         connection.close();
         }catch(Exception e){
          System.out.println("\n error in closing client");
       }
          }
         private void sendmessage(String message){
           try{
          output.writeObject("CLIENT-"+message);
           output.flush();
           }catch(Exception e){
           chatwindow.append("\n error in sending message from client side");
             }
               }
            private void showmessage(final String m){
             SwingUtilities.invokeLater( new Runnable(){
             public void run(){
            chatwindow.append(m);
           }
              }
                 );
                       }

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



    Client.java-> access client file code

           import javax.swing.JFrame;

          public class client {
           public static void main(String args[]){
         clientfile obj2= new clientfile("127.0.0.1");
          obj2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            obj2.startrunning();
              }        
                 }

What i want to know is how can i access chat in two different computer? Is it possible?

我想知道的是如何在两台不同的计算机上访问聊天?是否可以?

I want server.java on one computer & client.java on another computer. Please if anyone have any solution, let me know. feel free to ask questions.

我想要一台计算机上的 server.java 和另一台计算机上的 client.java。请如果有人有任何解决方案,请告诉我。随意问的问题。

回答by Sithsu

Yes, its possible to run server and client in two hosts.
Change your clientclass to accept IP of server in some way - through command line arguement, through keyboard input, etc. - instead of hardcoding "127.0.0.1" which is localhost

是的,可以在两台主机上运行服务器和客户端。
更改您的client类以某种方式接受服务器的 IP - 通过命令行争论,通过键盘输入等 - 而不是硬编码“127.0.0.1”,即本地主机

import javax.swing.JFrame;

public class client {
    public static void main(String args[]){
        clientfile obj2= new clientfile(args[0]); // taken from command line args
        obj2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj2.startrunning();
    }        
}

And run the client as java client 192.168.0.3where 192.168.0.3need to be replaced with the private IP of the host running your server.
IP of host running server can be obtained by executing ipconfigin windows or ifconfigin Linux/Ubuntu.

java client 192.168.0.3192.168.0.3需要替换为运行服务器的主机的私有 IP 的地方运行客户端。
主机运行服务器的IP可以ipconfig在windows或ifconfigLinux/Ubuntu中执行获得。

回答by Sai Sunder

Suppose your server program is running on system with ip 110.10.9.8(just a sample) In the client code line connection= new Socket(InetAddress.getByName(serverIP),6789);, replace InetAddress.getByName(serverIP)by 110.10.9.8. To know the IP of the server system just type "what is my IP" in goole. Remember that its dynamic IP and changes each time your modem or router restarts. So you have to find the IP each time. If you want to have something similar to static IP visit this

假设您的服务器程序在带有 ip 的系统上运行110.10.9.8(只是一个示例)在客户端代码行中connection= new Socket(InetAddress.getByName(serverIP),6789);,替换InetAddress.getByName(serverIP)110.10.9.8. 要知道服务器系统的 IP,只需在 goole 中输入“我的 IP 是什么”。请记住,它的动态 IP 会在您的调制解调器或路由器每次重新启动时更改。所以每次都得找IP。如果你想有类似静态 IP 的东西访问这个