简体   繁体   中英

how to implement multiple client-server chat

I have a client-server communication code. but, I actually want multiple clients communicating with the server not other clients, how should I implement it?

// This is server code:

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

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("Admin");
        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("\nYou have an error in conversation with client");
                } finally {
                    closecrap();
                }
            }
        } catch (Exception e) {
            System.out.println("\nYou have an error in connecting with client");
        }
    }

    private void waitForConnection() throws IOException {

        showmessage("\nWaiting for someone to connect");
        connection = server.accept();
        showmessage("\nNow connected to "
                + connection.getInetAddress().getHostName());
    }

    private void setupstream() throws IOException {

        output = new ObjectOutputStream(connection.getOutputStream());
        output.flush();
        input = new ObjectInputStream(connection.getInputStream());
        showmessage("\nStreams are setup");
    }

    private void whilechatting() throws IOException {

        String message = "\nYou are now connected ";
        sendmessage(message);
        ableToType(true);
        do {
            try {
                message = (String) input.readObject();
                showmessage(message);
            } catch (Exception e) {
                System.out.println("\nError 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("\nError in closing server");

        }
    }

    private void sendmessage(String message) {

        try {
            chatwindow.append("\nSERVER: " + message);
            output.writeObject("\nSERVER: " + message);
            output.flush();
        } catch (Exception e) {
            chatwindow.append("\nError in sending message from server side");
        }
    }

    private void showmessage(final String text) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                chatwindow.append("\n" + text);
            }
        });
    }

    private void ableToType(final boolean tof) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                usertext.setEditable(tof);
            }
        });
    }

}

public class Server {
    public static void main(String args[]) {
        ServerFile server1 = new ServerFile();
        server1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        server1.startrunning();
    }
}



// and this is the client code:

import javax.swing.JFrame;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ClientFile extends JFrame { 

    private static final long serialVersionUID = 1L;
    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");
          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("\nYou have an error in coversation with server");
          }
          finally{
              closecrap();
          }
      }

      private void connecttoserver() throws IOException{
          showmessage("\nAttempting connection");
          connection =  new Socket(InetAddress.getByName("127.0.0.1"),6789);          
          showmessage("\nConnected to "+connection.getInetAddress().getHostName());
      }

      private void setupstream() throws IOException{
          output= new ObjectOutputStream(connection.getOutputStream());
          output.flush();
          input= new ObjectInputStream(connection.getInputStream());
          showmessage("\nStreams are good to go");
      }

      private void whilechatting()throws IOException{
          ableToType(true);
          do {
              try{
                  message = (String)input.readObject();
                  showmessage(message);
              }
              catch(Exception e){
                  System.out.println("\nError 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("\nError in closing client");
          }
      }

      private void sendmessage(String message){
          try{
              chatwindow.append("\nCLIENT: "+message);
              output.writeObject("\nCLIENT: "+message);
              output.flush();
          }
          catch(Exception e){
              chatwindow.append("\nError in sending message from client side");
          }
      }

      private void showmessage(final String m){
            SwingUtilities.invokeLater( new Runnable(){
            public void run(){
                chatwindow.append("\n"+m);
            }});
      }

      private void ableToType(final boolean tof){
          SwingUtilities.invokeLater( new Runnable(){
          public void run(){
          usertext.setEditable(tof);
         }});
      }
}

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();

       }        
}

Applying multithreading is a good solution, but when I applied, there gets connection extablished between only one client and one server.. Please help me to do this

Applying multithreading is a good solution, but when I applied, there gets connection extablished between only one client and one server.. Please help me to do this

I did not get through (and thus checked) all your code, but I noticed one thing:

in your startrunning() function you:

  • create a server socket
  • in an infine loop:
    • wait for a new connection
    • when there's a new connection call setupstream()
    • and chat using whilechatting()

so there, you will get only one new connection that will get its stream set up and chat. You can only have one thread serving your clients, so only the first one arrived will get served, until it releases the thread so another can connect.

You should instead do:

  • create a server socket
  • in an infine loop:
    • wait for a new connection
    • when there's a new connection:
    • create a new thread for that connection
    • call setupstream()
    • and chat using whilechatting()

There each client will get spawned into their own cosy thread, while the main thread is in its infinite loop waiting for new clients.

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM