2013-03-31 2 views
1

Я разработал приложение простого текстового чата с помощью апплетов в 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 на другом компьютере. Пожалуйста, если у кого-нибудь есть какое-либо решение, дайте мне знать. Не стесняйтесь задавать вопросы.

ответ

1

Да, его можно запустить сервер и клиент на двух хостах.
Измените client класс принимать IP сервера каким-то образом - через командную строку arguement, через ввод с клавиатуры и т.д. - вместо жесткого кодирования «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(); 
    }   
} 

и запустить клиент java client 192.168.0.3, где 192.168.0.3 необходимо заменить частным IP-адресом хоста, на котором запущен ваш сервер.
IP хост-сервера можно получить, выполнив ipconfig в Windows или ifconfig в Linux/Ubuntu.

+0

ok, так что вы хотите сказать, что мне нужно запустить мой клиент в командной строке с конкретным IP-адресом сервера? ... спасибо, я попробую это – puneetverma0711

+0

@ puneetverma0711 Вы можете принять ответ, если он решит вашу проблему. – Sithsu

1

Предположим, ваша программа-сервер работает на системе с IP 110.10.9.8 (только образец) В коде клиента линии connection= new Socket(InetAddress.getByName(serverIP),6789);, замените InetAddress.getByName(serverIP) на 110.10.9.8. Чтобы узнать IP-адрес серверной системы, просто введите «что такое IP-адрес» в goole. Помните, что его динамический IP-адрес и изменяется каждый раз, когда ваш модем или маршрутизатор перезапускаются. Поэтому вы должны каждый раз находить IP. Если вы хотите, чтобы что-то похожее на статический IP-адрес this

+0

@Apurv спасибо, я попробую это, давайте узнаем, если в случае, если у меня возникнет какая-то проблема – puneetverma0711

+0

@ puneetverma0711 Это ответ [Sai Sunder's] (http://stackoverflow.com/users/958470/sai-sunder). Я просто улучшено форматирование. – Apurv

Смежные вопросы