这篇文章主要为大家详细介绍了java实现多人聊天系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了java实现多人聊天系统的具体代码,供大家参考,具体内容如下
开发环境
Windows 7 操作系统
MyEclipse
聊天室程序结构设计
1.系统分为客户端、服务器端和连接服务器客户端三个模块。
2.客户端负责发送消息。
3.服务器端负责接收客户端发来的信息并执行相应操作处理,最后通过群发功能,使客户端将群聊的消息的显示出来。
4.连接服务器端负责连接服务器,从而进入客户端。
总体模块图
客户端代码
Client.java
package servlet;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.OutputStreamWriter;
public class Client {
Socket socket;
BufferedWriter bw;
BufferedReader br ;
public Client(String ip, int port){
try {
socket =new Socket(ip,port);
bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
}catch (UnknownHostException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
public void sendMessage(String message) {
try{
bw.write(message);
bw.newLine();
bw.flush();
}catch(IOException e){
e.printStackTrace();
}
}
public String reciveMessage() {
String message=null;
try {
message = br.readLine();
}catch(IOException e) {
e.printStackTrace();
}
return message;
}
public void close(){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}}
ClientFrame.java
package servlet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ClientFrame extends JFrame {
private JPanel contentPane;
private JLabel lblUserName;
private JTextField tfMessage;
private JButton btnSend;
private JTextArea textArea;
private String userName;
private Client client;
public ClientFrame(String ip,String userName){
this.userName = userName;
init();//添加窗体初始化内容
addListener();
client=new Client(ip,8080);
ReadMessageThread t=new ReadMessageThread();
t.start();
}
private class ReadMessageThread extends Thread{
public void run() {
while(true) {
String str=client.reciveMessage();
textArea.append(str+"\n");//添加文本内容
}
}
}
private void init(){
setTitle("客户端");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100,100,450,300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5));
contentPane.setLayout(null);
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5,5,434,229);
contentPane.add(scrollPane);
textArea =new JTextArea();
scrollPane.setViewportView(textArea);
textArea .setEditable(false);
JPanel panel =new JPanel();
panel.setBounds(5,235,434,32);
contentPane.add(panel);
panel.setLayout(null);
lblUserName = new JLabel(userName);
lblUserName.setHorizontalAlignment(SwingConstants.TRAILING);
lblUserName.setBounds(2,4,55,22);
panel.add(lblUserName);
tfMessage =new JTextField();
tfMessage.setBounds(62,5,274,22);
tfMessage.setColumns(10);
panel.add(tfMessage);
btnSend =new JButton("发送");
btnSend.setBounds(336,4,93,23);
panel.add(btnSend);
tfMessage.validate();
}
private void addListener(){
btnSend.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Date date=new Date();
SimpleDateFormat sf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
client.sendMessage(userName+""+sf.format(date)+":\n"+tfMessage.getText());
tfMessage.setText("");//清空
}
});
this.addWindowListener(new WindowAdapter(){//开启窗口监听
public void windowClosing(WindowEvent atg0) {
int op = JOptionPane.showConfirmDialog(ClientFrame.this,"确定要退出聊天室吗?","确定",JOptionPane.YES_NO_OPTION);
if(op == JOptionPane.YES_OPTION) {
client.sendMessage("%EXIT%:" + userName);
try {
Thread.sleep(200);
}catch(InterruptedException e) {
e.printStackTrace();
}
client.close();
System.exit(0);
}
}
});
}
}
LinkServerFrame.java
package servlet;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
@SuppressWarnings("serial")
public class LinkServerFrame extends JFrame {
private JPanel contentPane;//下方面板
private JLabel lblIP;
private JLabel lblUserName;
private JTextField tfIP;
private JTextField tfUserName;
private JButton btnLink;
public LinkServerFrame(){
setTitle("连接服务器");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 390, 150);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5));
contentPane.setLayout(null);
setContentPane(contentPane);
lblIP =new JLabel("服务器IP地址:");
lblIP.setFont(new Font("微软雅黑",Font.PLAIN,14));
lblIP.setBounds(20,15,100,15);
contentPane.add(lblIP);
tfIP =new JTextField("127.0.0.1");
tfIP.setBounds(121,13,242,21);
contentPane.add(tfIP);
tfIP.setColumns(10);
lblUserName = new JLabel("用户名:");
lblUserName.setFont(new Font("微软雅黑",Font.PLAIN,14));
lblUserName.setBounds(60,40,60,15);
contentPane.add(lblUserName);
tfUserName =new JTextField();
tfUserName.setBounds(121,42,242,21);
contentPane.add(tfUserName);
tfUserName.setColumns(10);
btnLink =new JButton("连接服务器");
btnLink.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
do_btnlink_actionPerformed(e);
}
});
btnLink.setFont(new Font("微软雅黑",Font.PLAIN,14));
btnLink.setBounds(140,80,120,23);
contentPane.add(btnLink);//显示连接服务器窗口
}
public static void main(String[] args){
LinkServerFrame linkServerFrame = new LinkServerFrame();
linkServerFrame.setVisible(true);
}
protected void do_btnlink_actionPerformed(ActionEvent e) {
if(!tfIP.getText().equals("")&&!tfUserName.getText().equals("")) {//文本框的内容不能为空
dispose();//销毁当前窗口
ClientFrame clientFrame=new ClientFrame(tfIP.getText().trim(), tfUserName.getText().trim());
clientFrame.setVisible(true);//显示客户窗体
}
else {
JOptionPane.showMessageDialog(null,"文本框里的内容不能为空!","警告",JOptionPane.WARNING_MESSAGE);
}
}
}
服务器端代码
Server.java
package servlet;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Server {
private HashSet<Socket> allSocket;
private ServerSocket server;
public Server() {
try {
server = new ServerSocket(8080);
}catch(IOException e) {
e.printStackTrace();
}
allSocket=new HashSet<Socket>();
}
public void startServer() throws IOException{
while(true) {
Socket socket =server.accept();
System.out.println("用户已经进入聊天室");
allSocket.add(socket);
ServerThread t= new ServerThread(socket);
t.start();
}
}
private class ServerThread extends Thread{
Socket socket;
public ServerThread(Socket socket) {
this.socket=socket;
}
public void run() {
BufferedReader br=null;
try {
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true) {
String str=br.readLine();
if(str.contains("%EXIT%")) {
String tmp=str.split(":")[1]+"用户退出聊天室";
sendMessageToALLClient(tmp);
allSocket.remove(socket);
socket.close();
return;
}
sendMessageToALLClient(str);
}
}catch(IOException e) {
e.printStackTrace();
}
}}
private void sendMessageToALLClient(String str) throws IOException {
for(Socket s: allSocket) {
try{
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write(str);
bw.newLine();
bw.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Server s = new Server();
try {
s.startServer();
}catch(IOException e){
e.printStackTrace();
}
}
}
操作步骤
1.先运行服务器端代码(server.java)建立连接,然后运行客户端(LinkServerFrame.java)输入用户名
2.登入成功之后会显示用户已经进入聊天室
3.进入多人聊天室
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:java实现多人聊天系统
基础教程推荐
猜你喜欢
- java实现多人聊天系统 2023-05-19
- Java数据结构之对象比较详解 2023-03-07
- Java并发编程进阶之线程控制篇 2023-03-07
- Java实现查找文件和替换文件内容 2023-04-06
- Java实现线程插队的示例代码 2022-09-03
- java基础知识之FileInputStream流的使用 2023-08-11
- Java文件管理操作的知识点整理 2023-05-19
- JDK数组阻塞队列源码深入分析总结 2023-04-18
- ConditionalOnProperty配置swagger不生效问题及解决 2023-01-02
- springboot自定义starter方法及注解实例 2023-03-31