2015-03-13 142 views
0

大家好!聊天Java - 服務器故障

所以是的,我試圖與Java聊天功能。問題是我有兩個班。一個用於客戶端,另一個用於ClientGUI。凡客戶有邏輯事物和ClientGUI的設計。越來越問題是在排46,其中new ListenFromServer().start();是得到一個誤差

「型控制器的任何外圍實例是可訪問的,與型egxnew A()的包封實例 控制器(其中x是必須 資格分配控制器的一個實例)。「

我希望有人能幫助我這個!

**Controller (Client logic)** 

package Server; 

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




public class Controller { 

    private static ObjectInputStream input; 
    private static ObjectOutputStream output; 
    private static Socket socket; 
    private static ClientGUI clientgui; 

    private static String username; 
    private static String server; 
    private static int port; 



    public static boolean startClient(){ 

     try{ 
      socket = new Socket(server, port); 
     }catch (Exception ex){ 
      System.out.print("Error connecting to the server: " + ex); 
      return false; 
     } 

     String message = "Connection is accepted; " + socket.getInetAddress() +" - "+ socket.getPort(); 
     System.out.println(message); 


    try { 
     input=new ObjectInputStream(socket.getInputStream()); 
     output =new ObjectOutputStream(socket.getOutputStream()); 
    } 
    catch (IOException io) { 
     System.out.print("Exception creating new Input/Output Stream: "+ io); 
     return false; 

    } 

    **********new ListenFromServer().start();********* //The problem is here 

    try { 
     output.writeObject(username); 
    } 
    catch(IOException io) { 
     System.out.print("Exception doing login: " + io); 
     disconnect(); 
     return false; 
    } 
    return true; 
    } 

    private void display(String message) { 
     if(clientgui == null) 
      System.out.println(message); 
     else 
      clientgui.append(message +"\n"); 
    } 

    public static void sendMessage(Message message) { 
     try { 
      output.writeObject(message); 
     } 
     catch(IOException exd) { 
      System.out.print("Eceptionwritingtoserver: " + exd); 
     } 
    } 

    private static void disconnect() { 
     try { 
      if(input != null) 
       input.close(); 
     }catch (Exception ex){} 
     try{ 
      if(output != null) 
       output.close(); 
     }catch(Exception ex){} 
     try{ 
      if(socket != null) 
       socket.close(); 
     }catch(Exception ex){}; 

     if (clientgui != null) 
      clientgui.connectionFailed(); 
     } 

    public class ListenFromServer extends Thread{ 


     public void run() { 
      while(true){ 
       try{ 
        String message = (String) input.readObject(); 
        if(clientgui == null){ 
         System.out.println(message); 
         System.out.print(":"); 
        } 
        else { 
         clientgui.append(message); 
        } 
       } 
       catch(IOException io){ 
        System.out.print("Server has closed the connection"); 
        if(clientgui != null) 
         clientgui.connectionFailed(); 
        break; 
       } 
       catch(ClassNotFoundException classex){ 

       } 

       } 


      } 

     } 

    } 

ClientGUI

package Server; 
    import javax.swing.*; 
    import java.awt.*; 
    import java.awt.event.*; 


    /* 
    * The Client with its GUI 
    */ 
    public class ClientGUI extends JFrame implements ActionListener { 

     private static final long serialVersionUID = 1L; 

     private JLabel lblusername; 

     private JTextField textfieldusername, textfieldserver, textfieldportnumber; 

     private JButton btnlogin, btnlogout, btnonline; 

     private JTextArea textareamessage; 

     private boolean connected; 

     private Client client; 

     private int defaultPort; 
     private String defaultHost; 


     ClientGUI(String host, int port) { 

      super("Chat Client"); 
      defaultPort = port; 
      defaultHost = host; 


      JPanel northPanel = new JPanel(new GridLayout(2,2)); 
      JPanel serverAndPort = new JPanel(new GridLayout(1,2, 2, 2)); 
      JLabel lblserveraddress = new JLabel("Server Address: "); 
      JLabel lblchat = new JLabel("    #BallIsLife"); 
      JLabel lblportnumber = new JLabel("Port Number: "); 

      textfieldserver = new JTextField(host); 
      textfieldserver.setHorizontalAlignment(SwingConstants.LEFT); 
      textfieldserver.setFont(new Font("Tahoma", Font.PLAIN, 20)); 
      textfieldportnumber = new JTextField("" + port); 
      textfieldportnumber.setFont(new Font("Tahoma", Font.PLAIN, 20)); 
      textfieldportnumber.setHorizontalAlignment(SwingConstants.LEFT); 

      lblserveraddress.setFont(new Font("Tahoma", Font.PLAIN, 19)); 
      serverAndPort.add(lblserveraddress); 
      serverAndPort.add(textfieldserver); 
      serverAndPort.add(lblchat); 
      serverAndPort.add(lblportnumber); 
      serverAndPort.add(textfieldportnumber); 
      lblchat.setForeground(Color.RED); 
      lblportnumber.setFont(new Font("Tahoma", Font.PLAIN, 19)); 
      northPanel.add(serverAndPort); 
      getContentPane().add(northPanel, BorderLayout.NORTH); 

      JPanel panelbtn = new JPanel(); 
      northPanel.add(panelbtn); 


      btnlogin = new JButton("Login"); 
      panelbtn.add(btnlogin); 
      btnlogin.setFont(new Font("Tahoma", Font.PLAIN, 17)); 
      btnlogin.addActionListener(this); 

      btnonline = new JButton("Online"); 
      panelbtn.add(btnonline); 
      btnonline.setFont(new Font("Tahoma", Font.PLAIN, 17)); 

      btnonline.addActionListener(this); 
      btnonline.setEnabled(false);   

      btnlogout = new JButton("Logout"); 
      panelbtn.add(btnlogout); 
      btnlogout.setFont(new Font("Tahoma", Font.PLAIN, 17)); 
      btnlogout.addActionListener(this); 
      btnlogout.setEnabled(false);   

      JButton btnPicture = new JButton("Picture"); 
      btnPicture.setFont(new Font("Tahoma", Font.PLAIN, 17)); 
      btnPicture.setEnabled(false); 
      panelbtn.add(btnPicture); 


      textareamessage = new JTextArea("Welcome to the #BallIsLife Chat room.\n"); 
      textareamessage.setFont(new Font("Monospaced", Font.PLAIN, 15)); 

      textareamessage.setLineWrap(true); 
      textareamessage.setEditable(false); 

      JPanel centerPanel = new JPanel(new GridLayout(1,1)); 
      JScrollPane scrollPane = new JScrollPane(textareamessage); 
      centerPanel.add(scrollPane); 
      getContentPane().add(centerPanel, BorderLayout.CENTER); 


      JPanel southPanel = new JPanel(); 
      getContentPane().add(southPanel, BorderLayout.SOUTH); 

      lblusername = new JLabel("Enter your username", SwingConstants.CENTER); 
      lblusername.setFont(new Font("Tahoma", Font.PLAIN, 15)); 
      southPanel.add(lblusername); 

      textfieldusername = new JTextField("Write your username here."); 
      textfieldusername.setFont(new Font("Tahoma", Font.PLAIN, 14)); 
      textfieldusername.setColumns(50); 

      southPanel.add(textfieldusername); 


      setDefaultCloseOperation(EXIT_ON_CLOSE); 
      setSize(823, 665); 
      setVisible(true); 

     } 

    //Logiken 

     void append(String str) { 
      textareamessage.append(str); 
      textareamessage.setCaretPosition(textareamessage.getText().length() - 1); 
     } 


     void connectionFailed() { 
      btnlogin.setEnabled(true); 
      btnlogout.setEnabled(false); 
      btnonline.setEnabled(false); 
      lblusername.setText("Enter your username"); 
      textfieldusername.setText("Write your username here"); 

      textfieldportnumber.setText("" + defaultPort); 
      textfieldserver.setText(defaultHost); 

      textfieldserver.setEditable(false); 
      textfieldportnumber.setEditable(false); 

      textfieldusername.removeActionListener(this); 
      connected = false; 
     } 

     // 

     public void actionPerformed(ActionEvent e) { 
      Object button = e.getSource(); 

      if(button == btnlogout) { 
       Controller.sendMessage(new Message("", Message.LOGOUT)); //Ändra till Chatmessage klass 
       btnlogin.setText("Login"); 
       return; 
      } 

      if(button == btnonline) { 
       Controller.sendMessage(new Message("", Message.ONLINE)); //Ändra till Chatmessage klass   
       return; 
      } 


      if(connected) { 

       Controller.sendMessage(new Message(textfieldusername.getText(), Message.MESSAGE)); //Ändra till Chatmessage klass  
       textfieldusername.setText(""); 
       return; 
      } 


      if(button == btnlogin) { 

       String username = textfieldusername.getText(); 

       if(username.length() == 0) 
        return; 

       String server = textfieldserver.getText(); 
       if(server.length() == 0) 
        return; 

       String portNumber = textfieldportnumber.getText(); 
       if(portNumber.length() == 0) 
        return; 


       int port = 0; 
       try { 
        port = Integer.parseInt(portNumber); 
       } 
       catch(Exception en) { 
        return; 
       } 


       client = new Client(server, username, port, this); 

       if(!Controller.startClient()) 
        return; 

       } 

       connected = true; 

       textfieldusername.setText(""); 
       btnlogin.setText("Send message"); 


       btnlogin.setEnabled(true); 

       btnlogout.setEnabled(true); 
       btnonline.setEnabled(true); 

       textfieldserver.setEditable(false); 
       textfieldportnumber.setEditable(false); 

       textfieldusername.addActionListener(this); 
      } 



     // to start the whole thing the server 
     public static void main(String[] args) { 
      new ClientGUI("localhost", 1500); 
     } 

    } 
+0

可能有[Java的重複 - 沒有可以訪問Foo類型的封閉實例](http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – fabian 2016-03-04 00:20:41

回答

0

看看這個,嵌套類。如果嵌套的內部類是而不是靜態,則它可以訪問外部對象及其字段。這裏Inner類有一個Outer.this。對於new Inner()的分配,則必須提供外部對象:outer.new Inner()。一般來說,可以首先嚐試使內部類爲靜態,以查看是否需要外部類。

class Outer { 

    String s; 

    void p() { 
     StaticInner x = new StaticInner(); 
     Inner y = this.new Inner(); 
    } 

    static class StaticInner { 

     void f() { 
      // CANNOT use field s. 
     } 
    } 

    class Inner { 

     int n; 

     void g() { 
      n; 
      this.n; 
      this; 
      Outer.this; 
      Outer.this.s; 
      s; 
     } 
    } 
} 

最簡單的將是使你的內部類 「靜態」。

public static class ListenFromServer extends Thread{ 

一般人會到處static刪除,並創建只有一個控制器對象。這可以節省打字。

+0

這對我來說很難理解。你可以用我的代碼給exempel嗎?我試圖改變類ListenFromServer延伸線程{到一個靜態,但它給出了另一個錯誤:連接到服務器時出錯:java.net.ConnectException:連接:地址在本地計算機上無效,或端口在遠程計算機上無效。而且,如果我將公共靜態布爾startClient(){更改爲非靜態。它在ClientGUI中給出錯誤「if(!Controller.startClient()) \t \t \t \t return;」我需要有一個靜態的工作。 @ Joop-eggen – ThrillOfit 2015-03-13 15:22:55

+0

更新後。我現在得到的是:連接到服務器時出錯:java.net.ConnectException:connect:地址在本地機器上無效,或端口在遠程機器上無效 – ThrillOfit 2015-03-13 15:39:54

+0

帶有ServerSocket和'accept'的服務器我沒有見過;它必須在該插座上等待。 – 2015-03-13 15:44:45