2016-11-30 49 views
-1

此刻我正在創建一個簡單的聊天程序,它將允許您在服務器之間進行通信。當在另一個文件中的一個文件中使用時,我遇到訪問該用戶名變量的問題。用戶將輸入他的名字,這是在ChatGUI文件中完成的,然後當他進入聊天室時,會創建一個EchoFrame,它位於EchoFrame文件中。同樣在EchoFrame文件中,我希望將用戶名添加到用戶消息中,並且還會在他們連接到聊天室以及他們何時離開聊天室時發佈消息。我希望我清楚地解釋我的問題,還有其他需要的信息請告訴我!小型聊天程序,訪問文件之間的變量

EchoFrame

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

public class EchoFrame extends Frame{ 

    EchoPanel ep; 
    Button sendMessage; 

    public EchoFrame(){ 

     setSize(500,500); 
     setTitle("Echo Client"); 
     addWindowListener(new WindowAdapter(){ 
      public void windowClosing(WindowEvent we){ 
       System.exit(0); 
      } 
     }); 

     ep = new EchoPanel(); 
     add(ep, BorderLayout.CENTER); 




     setVisible(true); 
    } 

    public static void main(String[] args){ 

     EchoFrame ef = new EchoFrame(); 

    } 
} 


class EchoPanel extends Panel implements ActionListener, Runnable{ 

    TextField tf; 
    TextArea ta; 
    Button connect, disconnect; 
    Socket s; 
    BufferedReader br; 
    PrintWriter pw; 
    Thread t; 
    String fromServer; 
    String username; 


    public EchoPanel(){ 

     setLayout(new BorderLayout()); 
     tf = new TextField(); 
     tf.setEditable(false); 
     tf.addActionListener(this); 
     add(tf, BorderLayout.NORTH); 
     ta = new TextArea(); 
     ta.setEditable(false); 
     add(ta, BorderLayout.CENTER); 
     Panel buttonPanel = new Panel(); 
     connect = new Button("Connect"); 
     connect.addActionListener(this); 
     buttonPanel.add(connect); 
     disconnect = new Button("Disconnect"); 
     disconnect.setEnabled(false); 
     disconnect.addActionListener(this); 
     buttonPanel.add(disconnect); 
     add(buttonPanel, BorderLayout.SOUTH); 



    } 

    public void actionPerformed(ActionEvent ae){ 

     if(ae.getSource() == connect){ 
      try{ 
       s = new Socket("127.0.0.1", 8189); 
       ta.append(username + " has entered the chat room. \n"); 
       br = new BufferedReader(new InputStreamReader(s.getInputStream())); 
       pw = new PrintWriter(s.getOutputStream(), true); 
      }catch(UnknownHostException uhe){ 
       System.out.println(uhe.getMessage()); 
      }catch(IOException ioe){ 
       System.out.println(ioe.getMessage()); 
      } 

      t = new Thread(this); 
      t.start(); 
      tf.setEditable(true); 
      connect.setEnabled(false); 
      disconnect.setEnabled(true); 
     }else if(ae.getSource() == disconnect){ 
      try{ 
       pw.close(); 
       br.close(); 
       s.close(); 
      }catch(IOException ioe){ 
       System.out.println(ioe.getMessage()); 
      } 
      t = null; 
      ta.append(username + " has disconnected from chat room. \n"); 
      tf.setEditable(false); 
      connect.setEnabled(true); 
      disconnect.setEnabled(false); 
     }else if(ae.getSource() == tf){ 
      String fromTf = tf.getText(); 
      pw.println(fromTf); 
      tf.setText(""); 

     }else{ 

       //additional events 
     } 
    } 

    public void run(){ 
     fromServer = ""; 
     try{ 
      while((fromServer = br.readLine()) != null){ 

        ta.append(username + ":" + fromServer + "\n"); 
      } 
     }catch(IOException ioe){ 
      System.out.println(ioe.getMessage()); 
     } 
    } 

} 

ChatGUI

import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 
import java.net.*; 
import java.awt.BorderLayout; 
import java.awt.CardLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 




public class ChatGUI extends JFrame { 

    private int currentCard = 1; 
    private JPanel cardPanel; 
    private CardLayout cl; 
    JTextField usernameField; 
    String username; 

    public ChatGUI() { 

     setTitle("Chat Program"); 
     setSize(500, 120); 
     cardPanel = new JPanel(); 

     cl = new CardLayout(); 
     cardPanel.setLayout(cl); 

     JPanel chooseUsername = new JPanel(); 
     JLabel usernameLabel = new JLabel("Please enter your username:"); 

     chooseUsername.add(usernameLabel); 
     cardPanel.add(chooseUsername, "Log in"); 

     usernameField = new JTextField(15); 


     usernameField.setEditable(true); 
     add(usernameField, BorderLayout.CENTER); 


     JPanel buttonPanel = new JPanel(); 
     JButton logInBtn = new JButton("Enter Chat Room"); 

     buttonPanel.add(logInBtn); 



     logInBtn.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       currentCard = 2; 
       cl.show(cardPanel, "" + (currentCard)); 

       username = usernameField.getText(); //gets username 
       EchoFrame ef = new EchoFrame(); //creates message room 

      } 
     }); 


     getContentPane().add(cardPanel, BorderLayout.NORTH); 
     getContentPane().add(buttonPanel, BorderLayout.SOUTH); 
    } 
    public static void main(String[] args) { 
     ChatGUI cl = new ChatGUI(); 
     cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     cl.setVisible(true); 
    } 
} 

聊天服務器

import java.io.*; 
import java.net.*; 
import java.util.*; 

public class ChatServer{ 
    Socket s; 
    ArrayList <ChatHandler>handlers; 
    public ChatServer(){ 
     try{ 
      ServerSocket ss = new ServerSocket(8189); 
      handlers = new ArrayList<ChatHandler>(); 
      for(;;){ 
       s = ss.accept(); 
       new ChatHandler(s, handlers).start(); 
      } 
     }catch(IOException ioe){ 
      System.out.println(ioe.getMessage()); 
     } 
    } 
    public static void main(String[] args){ 
     ChatServer tes = new ChatServer(); 
    } 
} 

聊天處理器

import java.io.*; 
import java.net.*; 
import java.util.*; 

public class ChatHandler extends Thread{ 
    Socket s; 
    BufferedReader br; 
    PrintWriter pw; 
    String temp; 
    ArrayList <ChatHandler>handlers; 

    public ChatHandler(Socket s, ArrayList <ChatHandler>handlers){ 
     this.s = s; 
     this.handlers = handlers; 
    } 


    public void run(){ 
     try{ 
      handlers.add(this); 
      br = new BufferedReader(new InputStreamReader(s.getInputStream())); 
      pw = new PrintWriter(s.getOutputStream(), true); 
      temp = ""; 
      while((temp = br.readLine()) != null){ 
       for (ChatHandler ch : handlers){ 
        ch.pw.println(temp); 
       } 
       System.out.println(temp); 
      } 
     }catch(IOException ioe){ 
      System.out.println(ioe.getMessage());  
     }finally{ 
      handlers.remove(this); 
     } 
    } 
} 
+0

http://stackoverflow.com/help/mcve – nullpointer

回答

0

我認爲你應該有一個服務器程序和一個客戶端程序,所以你需要發送給每個客戶端的所有變量都可以進入服務器。

當客戶端連接到服務器時,您將該客戶端(用戶名,ipadress,無論)添加到連接的客戶端列表中,並創建一個新線程以偵聽/發送到該客戶端。然後從服務器,你可以發送給所有用戶(線程)的用戶名和他寫了什麼,如果你有一個函數sendToAll(idThreadSender,threadX.text),或者你可以sendtothread(threadX,threadY.text)以及我認爲你有一個壞結構,這就是一切。

希望我幫了忙。

+0

這是有道理的,如果只有我知道該怎麼做:o – Gillky

1

使userName靜態並通過ChatUI.userName訪問它。實際上,userName不應該在ChatUI。或者,如果您要擁有多個用戶,則更重要的選擇是獲取MySQL,設置數據庫並通過JDBC連接到該數據庫。

您還可以嘗試從這些示例中進行操作:Simple Client And Server Chat ProgramCreating a simple Chat Client/Server Solution。它們涵蓋了關鍵主題,如多線程。

+0

這實際上工作,非常感謝! – Gillky

+0

嗯我遇到了一個問題,它的工作,但在聊天GUI它不顯示每個名稱時有兩個GUIS打開。例如,如果羅斯和鮑勃聊天,它會看起來像羅斯是唯一一個在他的屏幕上說話 – Gillky

+0

你可以嘗試和從這些例子:[簡單客戶端和服務器聊天程序](http://www.dreamincode.net/forums/topic/262304-simple-client-and-server-chat-program /)和[創建一個簡單的聊天客戶端/服務器解決方案](http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual /Lectures/chat-c​​lient-server.html)。 –