java实现在线聊天系统
作者:sd訫訴sd 时间:2021-07-30 08:20:54
本文实例为大家分享了java实现在线聊天系统的具体代码,供大家参考,具体内容如下
本博客是博主在观看相关视频后写下的代码,希望能够帮助大家掌握java socket的相关知识。
原理介绍
代码展示
原理介绍
一、搭建服务器端
a)、创建ServerSocket对象绑定监听端口。
b)、通过accept()方法监听客户端的请求。
c)、建立连接后,通过输入输出流读取客户端发送的请求信息。
d)、通过输出流向客户端发送请求信息。
e)、关闭相关资源。
二、搭建客户器端
a)、创建Socket对象,指明需要连接的服务器的地址和端口。
b)、建立连接后,通过输出流向服务器发送请求信息。
c)、通过输入流获取服务器的响应信息。
d)、关闭响应资源
代码展示
服务器端代码:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
/**
* 版本三:转发给其他的客户端 1.保存每一个客户端的连接
*
*/
public class ChatSeverEdition3 {
// 服务器端是否启动
boolean started = false;
ServerSocket serverSocket = null;
ArrayList<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatSeverEdition3().start();
}
public void start() {
try {
serverSocket = new ServerSocket(8888);
started = true;
} catch (BindException e) {
// 多次启动服务器
System.out.println("端口使用中。。。。");
System.out.println("请关掉相关程序,并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while (started) {
// 客户端是否连接
Socket socket = serverSocket.accept();
// main()方法是static方法,不能在其中new动态类Client
Client client = new Client(socket);
// 线程启动
new Thread(client).start();
// 将当前启动的客户端保存下来
clients.add(client);
System.out.println("new Client成功!");
System.out.println("A Client connected!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
*
*
*/
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private boolean bConnected = false;
private DataOutputStream dos;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
System.out.println("有一个新的客户端程序在运行");
} catch (IOException e) {
e.printStackTrace();
}
// 一个客户端连接成功以后,一直在执行该while部分的代码,其他客户端无法连接
/**
* 解决方法: 1.异步解决方法:一直监听接收,其他在另外的地方执行 2.使用单独的线程: 线程:接受客户端连接
* 另外的单独的线程:处理通讯
*/
}
public void sendString(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("对方退出了!!!我从List中去掉了!!!");
}
}
public void run() {
Client client = null;
// 注意这部分的包围关系
try {
while (bConnected) {
String string = dis.readUTF();
System.out.println(string);
for (int i = 0; i < clients.size(); i++) {
client = clients.get(i);
client.sendString(string);
}
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
} finally {
try {
if (dis != null) {
dis.close();
}
if (s != null) {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
客户端代码:
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* 可以和ChatServer版本三配套使用
*
* @author Administrator
*
*/
public class ChatClientEdition3 extends Frame {
TextField tfText = new TextField();
TextArea taContent = new TextArea();
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
private boolean bConnected = false;
public static void main(String[] args) {
new ChatClientEdition3().launchFrame();
}
// 加载窗口
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
this.setTitle("在线聊天时--Quiana");
add(tfText, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
// 窗口关闭的时间监听
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}
});
tfText.addActionListener(new TFListener());
this.setVisible(true);
connect();
new Thread(new RecvThread()).start();
}
// 文字处理的时间监听
private class TFListener implements ActionListener {
// 敲击回车时,文字的变化事件
@Override
public void actionPerformed(ActionEvent arg0) {
String s = tfText.getText().trim(); // 去掉两端的空格
tfText.setText("");
try {
dataOutputStream.writeUTF(s);
dataOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 连接到服务器
public void connect() {
try {
// 连接到服务器
socket = new Socket("127.0.0.1", 8888);
bConnected = true;
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("连接到服务器!!!");
} catch (BindException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 断开连接
public void disconnect() {
try {
dataOutputStream.close();
System.out.println("dataOutputStream成功关闭");
socket.close();
System.out.println("客户端socket成功关闭");
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while (bConnected) {
String string = dataInputStream.readUTF();
if (taContent.getText().length() == 0) {
taContent.setText(string);
} else {
taContent.setText(taContent.getText() + "\n" + string);
}
}
} catch (SocketException e) {
System.out.println("退出了,拜拜!");
} catch (EOFException e) {
System.out.println("退出了,拜拜!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
来源:https://blog.csdn.net/qq_35864862/article/details/79184483
标签:java,聊天系统
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java针对ArrayList自定义排序的2种实现方法
2022-01-30 03:47:34
在Android设备上搭建Web服务器的方法
2023-06-23 23:38:36
![](https://img.aspxhome.com/file/2023/9/82419_0s.gif)
SpringBoot注册Servlet的三种方法详解
2022-06-15 15:56:29
![](https://img.aspxhome.com/file/2023/1/78921_0s.png)
Java实现将图片上传到webapp路径下 路径获取方式
2023-07-10 12:44:13
JAVA遍历Map集合的几种方法汇总
2021-09-01 12:34:07
SpringBoot整合支付宝APP支付
2021-10-12 02:57:24
![](https://img.aspxhome.com/file/2023/6/67476_0s.jpg)
C#从DataTable获取数据的方法
2022-09-16 03:20:59
java9学习系列之安装与jshell使用
2022-08-04 21:51:16
面试中遇到的java逃逸分析问题
2021-12-08 11:58:28
数组实现Java 自定义Queue队列及应用操作
2023-11-28 09:11:13
![](https://img.aspxhome.com/file/2023/0/60380_0s.png)
Springboot实现高吞吐量异步处理详解(适用于高并发场景)
2023-08-20 23:40:35
SWT(JFace)体验之模拟BorderLayout布局
2022-08-17 18:09:51
C#使用后台线程BackgroundWorker处理任务的总结
2023-12-08 10:28:19
![](https://img.aspxhome.com/file/2023/7/84427_0s.png)
Java开发SpringBoot集成接口文档实现示例
2022-07-14 05:43:50
![](https://img.aspxhome.com/file/2023/6/69326_0s.jpg)
Java多线程之同步工具类CountDownLatch
2023-10-23 22:17:51
![](https://img.aspxhome.com/file/2023/4/79834_0s.png)
源码浅析Android中内存泄漏检测工具Leakcanary的使用
2021-11-02 12:30:11
![](https://img.aspxhome.com/file/2023/8/88658_0s.png)
C#生成带二维码的专属微信公众号推广海报实例代码
2023-04-04 23:30:57
![](https://img.aspxhome.com/file/2023/7/79087_0s.jpg)
java多线程编程之join方法的使用示例
2022-10-06 05:09:38
Java 实现RSA非对称加密算法
2021-08-19 16:27:51
Java多线程实现简易微信发红包的方法实例
2023-04-16 11:46:15
![](https://img.aspxhome.com/file/2023/9/74919_0s.png)