java - 简单的文本聊天应用程序

标签 java applet

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

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

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

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

我的客户端代码:

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

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

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

最佳答案

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

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

并以 java client 192.168.0.3 运行客户端,其中 192.168.0.3 需要替换为运行服务器的主机的私有(private) IP。
运行服务器的主机IP可以通过在Windows中执行ipconfig或在Linux/Ubuntu中执行ifconfig来获取。

关于java - 简单的文本聊天应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15729989/

相关文章:

java - android应用程序存储ArrayList内容的最佳方法?

java - 从 jar 文件写入 $HOME

java - Hibernate 生成重复的 UUID

java - 知道如何为下面的代码编写 UT 吗?

java - 已签名的 Jar 和 doPrivileged 无法解决访问控制异常

c# - 通过方法设置变量与设置实际变量的区别

java - 如何从 Java Applet 检测当前安全上下文

java - 在 Java Applet 中显示网页

java - 为什么这个小程序不工作/显示图像?

java - 如何监控在浏览器中运行的Java Applet 的错误日志?