欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 聊天室实现

程序员文章站 2022-10-04 09:48:27
用Java实现聊天室功能聊天室功能分为两个部分,一部分是服务器的代码实现,一部分是客户端的代码实现,那么如何实现服务器和客户端的通信连接,如何实现客户端和客户端之间的信息通信就是我们要考虑的问题了。先看一下我们做出的聊天室效果:接下来上代码://首先是服务器主程序代码package chatroom;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;/*** @descrip...

用Java实现聊天室功能

聊天室功能分为两个部分,一部分是服务器的代码实现,一部分是客户端的代码实现,那么如何实现服务器和客户端的通信连接,如何实现客户端和客户端之间的信息通信就是我们要考虑的问题了。

先看一下我们做出的聊天室效果:

Java 聊天室实现

接下来上代码:

//首先是服务器主程序代码
package chatroom;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
* @description:
* @date:created in 2020-07-08 16:19
* @author:Dylan
* @modified by:
*/
public class ChatServer {
 //主函数入口
 public static void main(String[] args) throws IOException {
     //实例化一个服务器类的对象
     ChatServer cs=new ChatServer();
     //调用方法,为指定端口创建服务器
     cs.setUpServer();
 }
 private void setUpServer() throws IOException {
     // TODO Auto-generated method stub
     ServerSocket server=new ServerSocket(9000);
     //打印出当期创建的服务器端口号
     System.out.println("服务器创建成功!端口号:"+ 9000);
     while(true) {
         //等待连接进入
         Socket socket=server.accept();
         System.out.println("进入了一个客户机连接:"+socket.getRemoteSocketAddress().toString());
         //启动一个线程去处理这个对象
         ServerThread st=new ServerThread(socket);
         st.start();
     }
  }
}

//聊天室线程代码
package chatroom;

import java.io.*;
import java.net.Socket;

/**
 * @description:
 * @date:created in 2020-07-08 16:21
 * @author:Dylan
 * @modified by:
 */
public class ServerThread extends Thread {
    private Socket client;//线程中的处理对象
    private OutputStream ous;//输出流对象
    private UserInfo user;//用户信息对象

    public ServerThread(Socket client) {
        this.client=client;
    }

    public UserInfo getOwerUser() {
        return this.user;
    }

    @Override
    public void run() {
        try {
            processSocket();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //在显示屏中打印信息,例如"用户名"、"密码"等等
    public void sendMsg2Me(String msg) throws IOException {
        msg+="\r\n";
        ous.write(msg.getBytes());
        ous.flush();
    }
    private void processSocket() throws IOException {
        // TODO Auto-generated method stub
        InputStream ins=client.getInputStream();
        ous=client.getOutputStream();
        BufferedReader brd=new BufferedReader(new InputStreamReader(ins));

        sendMsg2Me("欢迎你来聊天,请输入你的用户名:");
        String userName=brd.readLine();
        sendMsg2Me("请输入密码:");
        String pwd=brd.readLine();
        user=new UserInfo();
        user.setName(userName);
        user.setPassword(pwd);
        //调用数据库,验证用户是否存在
        boolean loginState=DaoTools.checkLogin(user);
        if(!loginState) {
            //如果不存在这个账号则关闭
            this.closeMe();
            return;
        }
        sendMsg2Me("是否加入聊天:");
        String input=brd.readLine();
        if("是".equals(input)){
            sendMsg2Me("你已加入聊天");
        }
        ChatTools.addClient(this);//认证成功,把这个用户加入服务器队列
        while(!input.equals("bye")) {
            input=brd.readLine();
            System.out.println("服务器读到的是:"+input);
            ChatTools.castMsg(this.user, input);
        }
        ChatTools.castMsg(this.user, "bye");
        this.closeMe();
    }

    //关闭当前客户机与服务器的连接。
    public void closeMe() throws IOException {
        client.close();
    }
}

//服务器向客户分发消息代码
package chatroom;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @description:
 * @date:created in 2020-07-08 16:32
 * @author:Dylan
 * @modified by:
 */
public class ChatTools {
    //保存线程处理的对象
    private static final ArrayList<ServerThread> stList=new ArrayList();
    //不需要实例化类,因此构造器为私有
    private ChatTools() {}

    //将一个客户对应的线程处理对象加入到队列中
    public static void addClient(ServerThread st) throws IOException {
        stList.add(st);//将这个线程处理对象加入到队列中
        castMsg(st.getOwerUser(),"我上线了!目前人数:"+stList.size());
    }

    //发送消息给其他用户
    public static void castMsg(UserInfo sender,String msg) throws IOException {
        msg = sender.getName() + "说:" + msg;//加上说的对象
        for (int i = 0; i < stList.size(); i++) {
            ServerThread st = stList.get(i);
            st.sendMsg2Me(msg);//发消息给每一个客户机
        }
    }
}
```java
package chatroom;
//用户数据库代码
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @date:created in 2020-07-08 16:23
 * @author:Dylan
 * @modified by:
 */
public class DaoTools {
    //内存用户信息数据库
    private static Map<String, UserInfo> userDB = new HashMap();

    //静态块:模拟生成内存中的用户数据,用户名为1~10
    //当程序启动时这段代码会自动执行向userDB放入数据
    static {
        for (int i = 1; i <= 10; i++) {
            UserInfo user = new UserInfo();
            user.setName("Dylan"+i);
            user.setPassword("123456");
            userDB.put(user.getName(), user);
        }
    }

    public static boolean checkLogin(UserInfo user) {
        //在只验证用户名是否存在
        //return true;
        if (userDB.containsKey(user.getName())) {
            System.out.println("用户验证成功");
            return true;
         }
        System.out.println(user.getName() + "用户验证失败!");
        return false;
    }
}

//用户信息初始化代码
package chatroom;
/**
 * @description:
 * @date:created in 2020-07-08 16:22
 * @author:Dylan
 * @modified by:
 */
public class UserInfo {
    private String name;//用户名
    private String password;//密码
    private String loignTime;//登录时间
    private String address;//客户机端口名
    public String getName() {
        return name;
    }
    public void setName(String name) {
        // TODO Auto-generated method stub
        this.name=name;
    }
    public void setPassword(String psw) {
        this.password=password;
        }
}

接下来时客户端程序代码

//客户端主程序代码
package chatroom;

import java.io.*;
import java.net.Socket;

/**
 * @description:
 * @date:created in 2020-07-11 17:50
 * @author:Dylan
 * @modified by:
 */
public class ClientThread extends Thread{
    private  Socket socket ;

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

    @Override
    public void run() {
        while(true){
            try {
                getMsg();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    public void getMsg() throws IOException {
        InputStream is = socket.getInputStream();
        BufferedReader bis = new BufferedReader(new InputStreamReader(is));
        String i = bis.readLine();
        System.out.println(i);
        if("bye".equals(i)){
            socket.close();
        }
    }
}

//客户端1主程序代码
package chatroom;

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

/**
 * @description:
 * @date:created in 2020-07-08 16:35
 * @author:Dylan
 * @modified by:
 */
public class ChatClient {
    private static  Socket socket ;
    private static  OutputStream os ;
    public ChatClient() throws IOException { }

    public static void main(String[] args) throws IOException, InterruptedException {
        socket = new Socket("localhost",9000);
        InputStream is = socket.getInputStream();
        BufferedReader bis = new BufferedReader(new InputStreamReader(is));
        Scanner input = new Scanner(System.in);
        System.out.println(bis.readLine());
        String s = input.nextLine();
        sentMessage(s);
        System.out.println(bis.readLine());
        String s1 = input.nextLine();
        sentMessage(s1);
        System.out.println(bis.readLine());
        String s2 = input.nextLine();
        sentMessage(s2);
        System.out.println(bis.readLine());
        ClientThread ct = new ClientThread(socket);
        ct.start();
        while(true){
            String s3 = input.nextLine();
            sentMessage(s3);
        }
    }
     public static void  sentMessage(String s) throws IOException {
         os = socket.getOutputStream();
         s += "\r\n";
         os.write(s.getBytes());
         os.flush();
     }
}

//客户端2代码
package chatroom;

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

/**
 * @description:
 * @date:created in 2020-07-08 17:29
 * @author:Dylan
 * @modified by:
 */
public class ChatClient2 {
    private static Socket socket ;
    private static OutputStream os ;
    public ChatClient2() throws IOException { }

    public static void main(String[] args) throws IOException {
        socket = new Socket("localhost",9000);
        InputStream is = socket.getInputStream();
        BufferedReader bis = new BufferedReader(new InputStreamReader(is));
        Scanner input = new Scanner(System.in);
        System.out.println(bis.readLine());
        String s = input.nextLine();
        sentMessage(s);
        System.out.println(bis.readLine());
        String s1 = input.nextLine();
        sentMessage(s1);
        System.out.println(bis.readLine());
        String s2 = input.nextLine();
        sentMessage(s2);
        System.out.println(bis.readLine());
        ClientThread ct = new ClientThread(socket);
        ct.start();
        while(true){
            String s3 = input.nextLine();
            sentMessage(s3);
        }
    }
    public static void  sentMessage(String s) throws IOException {
        os = socket.getOutputStream();
        s += "\r\n";
        os.write(s.getBytes());
        os.flush();
    }
}

通过上面这些代码,我们就可以愉快的实现一个简易聊天室功能了。

本文地址:https://blog.csdn.net/qq_41595139/article/details/107346589