Java Chat P2P代码建议/指导

时间:2014-12-08 00:47:23

标签: java sockets syntax p2p

我开发了代码来创建p2p聊天程序。我的ChatServer代码和ChatServerReturns编译,但我继续运行其他程序并得到错误,如"非法开始表达"在public static void ACTION_B_SEND和public static void ACTION_B_DISCONNECT上的ChatClientGUI代码上。我在public void SEND(String X)上的ChatCLIENT代码上得到了相同的错误。我不知道为什么会出现这些错误。 聊天服务器代码     import java.io. ;     import java.net。;     import java.util。;     import javax.swing。;

public class ChatServer
{
   //Array list to hold the Sockets
   public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
   //Array list to hold all of the users
   public static ArrayList<String> CurrentUsers = new ArrayList<String>();

   public static void main(String[] args) throws Exception
   {
      try
      {
         final int PORT = 2345;
         ServerSocket SERVER = new ServerSocket(PORT);
         System.out.println("Waiting for clients");

         while(true)
         {
            //create new socket object
            Socket SOCK = SERVER.accept();
            //add to array list of sockets
            ConnectionArray.add(SOCK);

            System.out.println("Client connected from:  "+SOCK.getLocalAddress().getHostName());

            AddUserName(SOCK);

            ChatServerReturn CHAT = new ChatServerReturn(SOCK);
            Thread X = new Thread(CHAT);
            X.start();
         }
        }
        catch(Exception X)
        {
         System.out.print(X);
        }
   }

   public static void AddUserName(Socket X) throws IOException
   {
      //Crreate scanner object
      Scanner INPUT = new Scanner(X.getInputStream());
      String UserName = INPUT.nextLine();
      CurrentUsers.add(UserName);

      for(int i = 1; i <= ChatServer.ConnectionArray.size(); i++)
      {
         Socket TEMP_SOCK = (Socket) ChatServer.ConnectionArray.get(i-1);
         PrintWriter OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
         OUT.println("!!!" + CurrentUsers);
         OUT.flush();
      }
   }
}

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

public class ChatServerReturn implements Runnable
{
   //Globals
   Socket SOCK;
   private Scanner INPUT;
   private PrintWriter OUT;
   String MESSAGE = "";

   public ChatServerReturn(Socket X)
   {
      this.SOCK = X;
   }

   public void CheckConnection() throws IOException
   {
      if(!SOCK.isConnected())
      {
         for(int i = 1; i <= ChatServer.ConnectionArray.size(); i++)
         {
            if(ChatServer.ConnectionArray.get(i) == SOCK)
            {
               ChatServer.ConnectionArray.remove(i);
            }
         } 

         for(int i = 1; i <= ChatServer.ConnectionArray.size(); i++)
         {
            Socket TEMP_SOCK = (Socket) ChatServer.ConnectionArray.get(i-1);
            PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
            TEMP_OUT.println(TEMP_SOCK.getLocalAddress().getHostName() + " disconnected.");
            TEMP_OUT.flush();
            //Show disconnection at SERVER
            System.out.println(TEMP_SOCK.getLocalAddress().getHostName() + " disconnected.");
         }
      }
   }

   public void run()
   {
      try
      {
         try
         {
            //Create scanner and printwriter object
            INPUT = new Scanner(SOCK.getInputStream());
            OUT = new PrintWriter(SOCK.getOutputStream());

            while(true)
            {
               CheckConnection();

               if(!INPUT.hasNext())
               {
                  return;
               }

               MESSAGE = INPUT.nextLine();

               System.out.println("Client said; " + MESSAGE);

               for(int i = 1; i <= ChatServer.ConnectionArray.size(); i++)
               {
                  //
                  Socket TEMP_SOCK = (Socket) ChatServer.ConnectionArray.get(i-1);
                  PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
                  TEMP_OUT.println(MESSAGE);
                  TEMP_OUT.flush();
                  System.out.println("Sent to: " + TEMP_SOCK.getLocalAddress().getHostName());
               }
            }
         }
         finally
         {
            SOCK.close();
         }
      }
      catch(Exception X)
      {
         System.out.print(X);
      }
   }
}

ChatClientGUI     import java.io. ;     import java.net。;     import java.util。;     import javax.swing。;

public class ChatClientGUI
{
   //Globals
   private static ChatCLIENT ChatClient;
   public static String UserName = "Anonymous";

   //GUI Globals for Home Page
   public static JFrame MainWindow = new JFrame();
   private static JButton B_UNFOLLOW = new JButton();
   private static JButton B_CONNECT = new JButton();
   private static JButton B_DISCONNECT = new JButton();
   private static JButton B_FOLLOW = new JButton();
   private static JButton B_SEND = new JButton();
   private static JLabel L_Message = new JLabel("Message: ");
   public static JTextField TF_Message = new JTextField(20);
   private static JLabel L_CONVERSATION = new JLabel();
   public static JTextArea TA_CONVERSATION = new JTextArea();
   private static JScrollPane SP_CONVERSATION = new JScrollPane();
   private static JLabel L_ONLINE = new JLabel();
   public static JList JL_ONLINE = new JList();
   private static JScrollPane SP_ONLINE = new JScrollPane();
   private static JLabel L_LoggedInAs = new JLabel();
   private static JLabel L_LoggedInAsBox = new JLabel();

   //GUI Globals for Login Screen
   public static JFrame LogInWindow = new JFrame();
   public static JTextField TF_UserNameBox = new JTextField(20);
   private static JButton B_ENTER = new JButton("ENTER");
   private static JLabel L_EnterUserName = new JLabel("Enter username: ");
   private static JPanel P_Login = new JPanel();

   public static void main(String args[])
   {
      BuildMainWindow();
      Initialize();
   }

   public static void Connect()
   {
      try
      {
         final int PORT = 2345;
         final String HOST = "The Plug";
         Socket SOCK = new Socket(HOST,PORT);
         System.out.println("You connected to: "+ HOST);

         //Passing to CHATCLIENT class
         ChatClient = new ChatCLIENT(SOCK);

         //Send Name to add to "Online" List
         PrintWriter OUT = new PrintWriter(SOCK.getOutputStream());
         OUT.println(UserName);
         OUT.flush();

         Thread X = new Thread(ChatClient);
         X.start();
      }
      catch(Exception X)
      {
         System.out.print(X);
         JOptionPane.showMessageDialog(null, "Server not responding.");
         System.exit(0);
      }
   }

   public static void Initialize();
   {
      B_SEND.setenabled(false);
      B_DISCONNECT.setEnabled(false);
      B_CONNECT.setEnabled(true);
   }

   public static void BuildLogInWindow()
   {
      LogInWindow.setTitle("Enter your name: ");
      LogInWindow.setSize(300,100);
      LogInWindow.setLocation(300,200);
      LogInWindow.setResizable(false);
      P_LogIn = new JPanel();
      P_LogIn.add(L_EnterUserName);
      P_LogIn.add(TF_UserNameBox);
      P_LogIn.add(B_ENTER);
      LogInWindow.add(P_LogIn);

      Login_Action();
      LogInWindow.setVisible(true);
   }

   public static void BuildMainWindow()
   {
      MainWindow.setTitle(UserName + "'s Chat Box");
      MainWindow.setSize(500,500);
      MainWindow.setLocation(200,200);
      MainWindow.setResizable(false);
      ConfigureMainWindow();
      MainWindow_Action();
      MainWindow.setVisible(true);
   }

   public static void ConfigureMainWindow()
   {
      MainWindow.setBackground(new java.awt.Color(255, 255, 255));
      MainWindow.setSize(500, 350);
      MainWindow.getContentPane().setLayout(null);

      B_SEND.setBackground(new java.awt.Color(0, 0, 255));
      B_SEND.setForeground(new java.awt.Color(255, 255, 255));
      B_SEND.setText("SEND");
      MainWindow.getContentPane().add(B_SEND);
      B_SEND.setBounds(250,40, 80, 25);

      B_DISCONNECT.setBackground(new java.awt.Color(0, 0, 255));
      B_DISCONNECT.setForegroudn(new java.awt.Color(255, 255, 255));
      B_DISCONNECT.setText("End Connection");
      MainWindow.getContentPane().add(B_DISCONNECT);
      B_DISCONNECT.setBounds(10, 40, 110, 25);

      B_CONNECT.setBackground(new java.awt.Color(0, 0, 255));
      B_CONNECT.setForeground(new java.awt.Color(255, 255, 255));
      B_CONNECT.setText("Connect");
      B_CONNECT.setToolTipText("");
      MainWindow.getContentPane().add(B_CONNECT);
      B_CONNECT.setBounds(10, 40, 110, 25);

      B_FOLLOW.setBackground(new java.awt.Color(0, 0, 255));
      B_FOLLOW.setForeground(new java.awt.Color(255, 255, 255));
      B_FOLLOW.setText("HELP");
      MainWindow.getContentPane().add(B_FOLLOW);
      B_FOLLOW.setBounds(10, 40, 110, 25);

      B_UNFOLLOW.setBackground(new java.awt.Color(0, 0, 255));
      B_UNFOLLOW.setForeground(new java.awt.Color(255, 255, 255));
      B_UNFOLLOW.setText("ABOUT");
      MainWindow.getContentPane().add(B_UNFOLLOW);
      B_UNFOLLOW.setBounds(300, 40, 75, 25);

      L_Message.setText("Message: ");
      MainWindow.getContentPane().add(L_MESSAGE);
      L_Message.setBounds(10, 10, 50, 20);

      TF_Message.setForeground(new java.awt.Color(0, 0, 255));
      TF_Message.requestFocus();
      MainWindow.getContentPane().add(TF_Message);
      TF_Message.setBounds(60, 5, 240, 30);

      L_Conversation.setHorizontalAlignment(SwingConstants.CENTER);
      L_Conversation.setText("Conversation");
      MainWindow.getContentPane().add(L_Conversation);
      L_Conversation.setBounds(100, 60, 120, 16);

      TA_CONVERSATION.setColumns(20);
      TA_CONVERSATION.setFont(new java.awt.Font("Arial", 0, 10));
      TA_CONVERSATION.setForeground(new java.awt.Color(0, 0, 255));
      TA_CONVERSATION.setLineWrap(true);
      TA_CONVERSATION.setRows(7);
      TA_CONVERSATION.setEditable(false);

                      SP_CONVERSATION.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
      SP_CONVERSATION.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
      SP_CONVERSATION.setViewportView(TA_CONVERSATION);
      MainWindow.getContentPane().add(SP_CONVERSATION);
      SP_CONVERSATION.setBounds(10, 100, 300, 150);

      L_ONLINE.setHorizontalAlignment(SwingConstants.CENTER);
      L_ONLINE.setText("Now Online");
      L_ONLINE.setToolTipText("");
      MainWindow.getContentPane().add(L_ONLINE);
      L_ONLINE.setBounds(300, 50, 150, 20);

      String [] TestNames = ("Brandon");
      String [] TestNames = ("Mike");
      String [] TestNames = ("Deloris"); 
      String [] TestNames = ("Crystal");
      JL_ONLINE.setForeground(new java.awt.Color(0, 0, 255));
      JL_ONLINE.setListData(TestNames);

      SP_ONLINE.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
      SP_ONLINE.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
      SP_ONLINE.setViewportView(JL_ONLINE);
      MainWindow.getContentPane().add(SP_ONLINE);
      SP_ONLINE.setBounds(350, 100, 100, 200);

      L_LoggedInAs.setFont(new java.awt.Font("Arial", 0, 10));
      L_LoggedInAs.setText("Logged In As: ");
      MainWindow.getContentPane().add(L_LoggedInAs);
      L_LoggedInAs.setBounds(300, 0, 150, 15);

      L_LoggedInAsBox.setHorizontalAlignment(SwingConstants.CENTER);
      L_LoggedInAsBox.setFont(new java.awt.Font("Arial", 0, 10));
      L_LoggedInAsBox.setForeground(new java.awt.Color(255, 0, 0));
      L_LoggedInAsBox.setBorder(BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
      MainWindow.getContentPane().add(L_LoggedInAsBox);
      L_LoggedInAsBox.setBounds(350, 20, 150, 20);
   }

   public static void Login_Action()
   {
       B_ENTER.addActionListener(
       new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.Actionevent evt)
         {
            ACTION_B_ENTER();
         }
      }
   );
}

   public static void ACTION_B_ENTER()
   {
      if(!TF_UserNameBox.getText().equals(""))
      {
          UserName = TF_UserNameBox.getText().trim();
          L_LoggedInAsBox.setText(UserName);
          ChatServer.CurrentUsers.add(UserName);
          MainWindow.setTitle(UserName + "'s Chat Box");
          LogInWindow.setVisible(false);
          B_SEND.setEnabled(true);
          B_DISCONNECT.setEnabled(true);
          B_CONNECT.setEnabled(false);
          Connect();
      }
      else
      {
         JOptionPane.showMessageDialog(null, "Please enter a name.");
      } 
   }

   public static void MainWindow_Action()
   {
      B_SEND.addActionListener(
      new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            ACTION_B_SEND();
         }
      }


      B_DISCONNECT.addActionListener(
      new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            ACTION_B_DISCONNECT();
         }
      };
   )

      B_CONNECT.addActionListener(
      new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            ACTION_B_CONNECT();
         }
      };
   )

      B_FOLLOW.addActionListener(
      new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            ACTION_B_FOLLOW();
         }
      };
   )
      B_UNFOLLOW.addActionListener(
      new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            ACTION_B_UNFOLLOW();
         }
      };
   )

   public static void ACTION_B_SEND()
   {
      if(!TF_Message.getText().equals(""))
      {
         ChatClient.SEND(TF_Message.getText());
         TF_Message.requestFocus();
      }
   }

   public static void ACTION_B_DISCONNECT()
   {
      try
      {
         ChatClient.DISCONNECT();
      }
      catch(Exception Y)
      {
         Y.printStackTrace();
      }
   }

}

ChatCLIENT代码     import java.net。;     import java.io。;     import java.util。;     import javax.swing。;

public class ChatCLIENT implements Runnable
{
   //Globals
   Socket SOCK;
   Scanner INPUT;
   Scanner SEND = new Scanner(System.in);
   PrintWriter OUT;

   public ChatCLIENT(Socket X)
   {
      this.SOCK = X;
   }

   public void run()
   {
      try
      {
         try
         {
            INPUT = new Scanner(SOCK.getInputStream());
            OUT = new PrintWriter(SOCK.getOutputStream());
            OUT.flush();
            CheckStream();
        } 
         finally
         {
            SOCK.close();
         }
      }
      catch(Exception X)
      {
         System.out.print(X);
      }
   }

   public void DISCONNECT() throws IOException
   {
      OUT.println(ChatClientGUI.UserName + " has disconnected.");
      OUT.flush();
      SOCK.close();
      JOptionPane.showMessageDialog(null, "You disconnected.");
      System.exit(0);
   }

   public void CheckStream()
   {
      while(true)
      {
         RECEIVE();
      }
   }

   public void RECEIVE()
   {
      if(INPUT.hasNext())
      {
         String MESSAGE = INPUT.nextLine();

         if(MESSAGE.contains("!!"))
         {
            String TEMP1 = MESSAGE.substring(3);
                   TEMP1 = TEMP1.replace("[","");
                   TEMP1 = TEMP1.replace("]","");

            String[] CurrentUsers = TEMP1.split(", ");

            ChatClientGUI.JL_ONLINE.setListData(CurrentUsers);
         }
         else
         {
            ChatClientGUI.TA_CONVERSATION.append(MESSAGE + "\n");
         }
      }

      public void SEND(String X);
      {
         OUT.println(ChatClientGUI.UserName + ": " + X);
         OUT.flush();
         ChatClientGUI.TF_Message.setText("");
      }
};

1 个答案:

答案 0 :(得分:0)

;之后移除public static void Initialize();                      - zapl