2011-04-13 9 views
1

나는 채팅하려고합니다. 내 질문은 사용자 목록을 열어 놓은 모든 프레임에서 볼 수 있도록 다른 사용자가 입력 한 경우 어떻게 사용자 목록을 새로 고칠 수 있습니까?모든 프레임의 사용자 목록 새로 고침

import java.io.*; 

public class MulticastChat implements Runnable, WindowListener, ActionListener { 
    public InetAddress groupp; 
    public int port; 

    public MulticastChat (InetAddress group, int port) throws IOException { 
    this.groupp = group; 
    this.port = port; 
    start(); 
    } 
    public String [] user; 
    public Frame frame; 
    public TextArea output; 
    public TextField input; 
    public Button button; 
    public Panel panel; 
    public Panel p; 
    public List list=new List(8); 
    public TextField tf; 

    public Thread listener; 



    protected MulticastSocket socket; 
    protected DatagramPacket outgoing, incoming; 

    protected void initNet() throws IOException { 
    socket = new MulticastSocket (port); 
    socket.setTimeToLive (5); 
    socket.joinGroup (groupp); 
    outgoing = new DatagramPacket (new byte[1], 1, groupp, port); 
    incoming = new DatagramPacket (new byte[65508], 65508); 

    } 
    public synchronized void start() throws IOException { 
    if (listener == null) { 
     initAWT(); 
     initNet(); 
     listener = new Thread (this); 
     listener.start(); 
     frame.setVisible (true); 

     list.add(frame.getTitle()); 
    } 
    } 

    public void initAWT() { 
    frame = new Frame 
    (); 
    frame.addWindowListener (this); 

    tf=new TextField(10); 
    output = new TextArea(); 
    output.setEditable (false); 
    button=new Button("Login"); 
    button.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 

     if (e.getActionCommand().equals("Login")) { 
      try { 
      if(!tf.getText().isEmpty()){ 

       byte[] utf = (tf.getText()+" Joined").getBytes ("UTF8"); 
       frame.setTitle(tf.getText()); 
       outgoing.setData (utf); 
       outgoing.setLength (utf.length); 
       socket.send (outgoing); 
       input.setText (""); 
       list.addItem(tf.getText()); 
       tf.setVisible(false); 
       button.setVisible(false); 
      }else{ 
       JOptionPane.showMessageDialog(frame, "Enter login name"); 
      } 
      } catch (IOException ex) { 
       handleIOException (ex); 
      } 
     } 
     } 
    }); 
    panel=new Panel(new BorderLayout()); 
    p=new Panel(new BorderLayout()); 
    input = new TextField(); 
    input.addActionListener (this); 
    frame.setLayout (new BorderLayout()); 
    panel.add(tf,"South"); 
    panel.add(list,"North"); 
    panel.add(button,"Center"); 
    frame.add(panel,"East"); 
    p.add (output, "Center"); 
    p.add (input, "South"); 
    frame.add(p,"West"); 
    frame.pack(); 

    } 


    public synchronized void stop() throws IOException { 
    String s=frame.getTitle(); 
    frame.dispose(); 

    byte[] utf = (s+"Leaved").getBytes ("UTF8"); 
     outgoing.setData (utf); 
     outgoing.setLength (utf.length); 
     socket.send (outgoing); 
    if (listener != null) { 
     listener.interrupt(); 
     listener = null; 
     try { 
     socket.leaveGroup (groupp); 
     } finally { 
     socket.close(); 
     } 
    } 
    } 

    public void windowOpened (WindowEvent event) { 
    input.requestFocus(); 
    } 

    public void windowClosing (WindowEvent event) { 
    try { 

     stop(); 

    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
    } 

    public void windowClosed (WindowEvent event) { 
    } 
    public void windowIconified (WindowEvent event) {} 
    public void windowDeiconified (WindowEvent event) {} 
    public void windowActivated (WindowEvent event) {} 
    public void windowDeactivated (WindowEvent event) {} 

    public void actionPerformed (ActionEvent event) { 
    try { 
     byte[] utf = event.getActionCommand().getBytes ("UTF8"); 
     outgoing.setData (utf); 
     outgoing.setLength (utf.length); 
     socket.send (outgoing); 
     input.setText (""); 


    } catch (IOException ex) { 
     handleIOException (ex); 
    } 
    } 

    protected synchronized void handleIOException (IOException ex) { 
    if (listener != null) { 
     output.append (ex + "\n"); 
     input.setVisible (false); 
     frame.validate(); 
     if (listener != Thread.currentThread()) 
     listener.interrupt(); 
     listener = null; 
     try { 
     socket.leaveGroup (groupp); 
     } catch (IOException ignored) { 
     } 
     socket.close(); 
    } 
    } 

    public void run() { 

    try { 

     while (!Thread.interrupted()) { 
     incoming.setLength (incoming.getData().length); 
     socket.receive (incoming); 
     String message = new String 
     (incoming.getData(), 0, incoming.getLength(), "UTF8"); 
     output.append (incoming.getAddress().toString()+frame.getTitle()+message + "\n"); 
     } 
    } catch (IOException ex) { 
     handleIOException (ex); 
    } 

    } 
    public void refresh(){ 

    } 

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

    InetAddress group; 

     group = InetAddress.getByName("235.235.235.235"); 

    int port = 2999; 
    new Thread(new MulticastChat(group, port)); 
    } 
} 

답변

1
  • 업데이트 특정 시간 간격 목록. (폴링 메커니즘) 해당 클라이언트 그래서 몇 가지 명령과 갱신에 필요한 반환 패킷이있는 경우
  • 이 클라이언트에서 일부 데이터 (해시)를 전송하고 서버에 그것을 확인 목록을 새로 고침
0

이 대답은 설명 적이 지 않지만 새로운 사용자가 채팅에 참여할 때 제어하기 위해 이벤트 처리기를 만들도록하십시오. 같은 뭔가 :

public void newUserIn (UserEvent event) {} 

정도 ...

0

첫째, 난 당신이 쉽게 읽고 유지 관리 할 수 ​​있도록, 수업의 번호로 코드를 분리 해 건의 할 것입니다. 네트워크 IO 용 클래스와 Window 용 클래스가 필요합니다. 두 가지를 리스너 인터페이스로 연결하십시오.

둘째, 사용자가 가입했다는 멀티 캐스트 메시지를 만들어야합니다. 이것은 "[NEW-USER : xxxxxx]"와 같을 수 있습니다.

그런 다음 클라이언트의 수신 메시지를 검사하여 '새 사용자'메시지를 식별해야합니다. 그런 다음 해당 사용자를 사용자 인터페이스에 표시 할 수 있습니다.

또한 사용자가 새 사용자 메시지를 스푸핑하지 못하게해야합니다. 새로운 사용자 패턴과 일치하는 것을 입력 할 경우 오판되지 않도록 이스케이프하십시오.

관련 문제