Network Chat Room Based on Socket Programming

Posted by Bramme on Tue, 30 Jul 2019 22:06:13 +0200

1. Project Profile:
Network Chat Room Based on Socket Programming
2. Functional description:
Multi-user registration, group distribution and private chat can be implemented:
3. Specific implementation process:
Client implementation process:
1. The functions of the client can be further refined as follows:
Send out information:
Accept information from other clients:
Since the sending and receiving functions should be independent, two threads are used to implement them separately:
1. Sending threads:
The main principle of internal implementation is to get the sokcet output stream and send information through the output stream.
2. Shut down Socket and quit chat if there is Bye

public class Write implements Runnable{
    private Socket socket;

    public Write(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
        	//Get the output stream
            PrintStream out=new PrintStream(socket.getOutputStream());
            Scanner scanner = new Scanner(System.in);
            String msg=null;
            while(true) {
                if(scanner.hasNext()) {
                    msg = scanner.next();
                }
                out.println(msg);
                if(msg.contains("Bye")){
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Accept information from other clients:
Technological process:
Get the input stream to read the information sent from the server:

class Read implements Runnable{
    private Socket socket;

    public Read(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        Scanner scanner= null;
        try {
            scanner = new Scanner(socket.getInputStream());
            while(true){
                System.out.println("Waiting for messages from clients");
                String str=null;
                if(scanner.hasNext()){
                    System.out.println(scanner.next());
                }
                if(socket.isClosed()){
                    break;
                }


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


    }
}

Server implementation process:
The function of a transfer station: classify the information sent to achieve the functions of registration, group distribution and private chat.
public class Services {
private static Map<String,Socket> map=new ConcurrentHashMap<String, Socket>();
static private class RealServices implements Runnable{
private Socket socket;

    public RealServices(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            Scanner in=new Scanner(socket.getInputStream());
            String msg=null;
            while(true){
                if(in.hasNext()) {
                    msg = in.next();
                }
                Pattern pattern = Pattern.compile("\r");
              java.util.regex.Matcher matcher = pattern.matcher(msg);
              //If you start with userName, you register by storing all user information in a map.
              if(msg.startsWith("userName")){
                  String username=msg.split(":")[1];
                  register(username);
                    continue;
              }
              //G begins with a group chat.
              if(msg.startsWith("G")){
                  String send=msg.split(":")[1];
                  group(send);
              }
              //Receiving the data P begins with a private chat
              if (msg.startsWith("P")){
                  String username=msg.split(":")[1].split("\\-")[0];
                  String send=msg.split("\\-")[1];
                  privateSend(username,send);
              }
              if(msg.contains("Bye")){
                  Set<Map.Entry<String, Socket>> entries = map.entrySet();
                  Iterator<Map.Entry<String,Socket>> iterator=entries.iterator();
                  String username=null;
                  Socket socket=null;
                  while(iterator.hasNext()){
                      Map.Entry<String,Socket> i=iterator.next();
                      username=i.getKey();
                       socket=i.getValue();
                      if(socket==this.socket){
                          iterator.remove();
                      }
                  }
                  group(username+"Withdrawal from group chat,There are still chat rooms left."+map.size());
                  System.out.println(username+"Withdrawal from group chat");
              }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void register(String username) throws IOException {
        if(map.containsKey(username)){
            System.out.println("The current user already exists");
        }else {
            map.put(username,socket);
            group("Welcome"+username+"Join the chat room, the current number of chat rooms:"+map.size());
            System.out.println("Welcome"+username+"Join the chat room, the current number of chat rooms:"+map.size());

        }
    }
	//Traversing the map set sends out each data
    private  void group(String send) throws IOException {
        Set<Map.Entry<String, Socket>> entries = map.entrySet();
        Iterator<Map.Entry<String,Socket>> iterator=entries.iterator();
        while (iterator.hasNext()){
            Map.Entry<String,Socket> i=iterator.next();
            Socket socket=i.getValue();
            if(socket==this.socket){
                continue;
            }
            PrintStream printStream=new PrintStream(socket.getOutputStream());
            printStream.println(send);
        }

    }
    //Private chat to get the specified user's Socket, create a connection to send
    private  void privateSend(String username, String send) throws IOException {
        Socket to=map.get(username);
        if(to==null){
            PrintStream out=new PrintStream(socket.getOutputStream());
            out.println("Current user does not exist");
        }else {
            PrintStream out=new PrintStream(to.getOutputStream());
            out.println("Send information: "+send);
        }
    }
}

Topics: socket network Programming Java