java利用Socket实现聊天室功能实例
作者:Eric_ley 时间:2022-11-10 01:25:43
最近研究了下Java socket通信基础,利用代码实现了一个简单的多人聊天室功能,现把代码共享下,希望能帮到有兴趣了解的人。
目录结构:
ChatClient:
package com.panda.chat;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
@SuppressWarnings("serial")
public class ChatClient extends Frame {
private TextArea ta = new TextArea();
private TextField tf = new TextField();
private DataOutputStream dos = null;
private DataInputStream dis = null;
private Socket socket = null;
private boolean bConnected = false;
private Thread thread=null;
public static void main(String[] args) {
new ChatClient().frameClient();
}
public void frameClient(){
setSize(400, 400);
setLocation(400,300);
add(ta,BorderLayout.NORTH);
add(tf,BorderLayout.SOUTH);
pack();
tf.addActionListener(new TfListener());
//关闭窗口事件监听
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
disconnected();
System.exit(0);
}
});
this.connect();
setVisible(true);
}
//链接服务器地址
private void connect(){
try {
socket = new Socket("127.0.0.1", 8888);
thread=new Thread(new ChatThread());
thread.start();
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//断开连接
private void disconnected(){
bConnected = false;
try {
dos.close();
dis.close();
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//键盘回车事件
private class TfListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String strMsg = tf.getText();
tf.setText("");
try {
dos.writeUTF(strMsg);
dos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
//开启线程接受服务器信息
private class ChatThread implements Runnable{
@Override
public void run() {
try {
bConnected = true;
while(bConnected){
String msg = dis.readUTF();
String taText = ta.getText();
ta.setText(taText+msg+"\n");
}
} catch (SocketException e) {
System.out.println("退出");;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ChatServer:
package com.panda.chat;
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private boolean started = false;
private List<ChatThread> chatThreads = new ArrayList<ChatThread>();
public static void main(String[] args) {
new ChatServer().startServer();
}
private void startServer(){
try {
//开启服务端Socket
ServerSocket seso = new ServerSocket(8888);
started = true;
while(started){
//接受客户端连接请求
Socket sos = seso.accept();
System.out.println("一个客户端已连接");
//开启线程处理客户端通信
ChatThread ct = new ChatThread(sos);
chatThreads.add(ct);
new Thread(ct).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class ChatThread implements Runnable{
private Socket socket;
private DataInputStream din=null;
private DataOutputStream don=null;
private boolean bConnected = false;
public ChatThread(Socket socket) {
super();
this.socket = socket;
}
//发送信息的函数
private void send(String strMsgIn){
try{
don.writeUTF(strMsgIn);
don.flush();
}catch(IOException e){
e.printStackTrace();
}
}
@Override
public void run() {
try{
din = new DataInputStream(socket.getInputStream());
don = new DataOutputStream(socket.getOutputStream());
//读取数据
bConnected = true;
while(bConnected){
String strMsgIn = din.readUTF();
System.out.println(strMsgIn);
//接收到数据后发送给每个客户端
for(int i =0;i<chatThreads.size();i++){
chatThreads.get(i).send(strMsgIn);
}
}
}catch (IOException e) {
try {
//如果客户端出错或关闭,直接关闭连接,并移除List中的当前线程
socket.close();
chatThreads.remove(this);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally{
try {
din.close();
don.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
运行ChatSever后,再同时打开多次ChatClient,就可以实现多人聊天了,你也试试。
来源:http://blog.csdn.net/eric_ley/article/details/54906931
标签:java,socket,聊天室
0
投稿
猜你喜欢
Flutter WebView 预加载实现方法(Http Server)
2023-06-25 23:14:35
全网最全SpringBoot集成swagger的详细教程
2021-10-25 16:53:44
SprinBoot如何集成参数校验Validator及参数校验的高阶技巧
2023-10-23 16:24:31
Android编程简单设置ListView分割线的方法
2021-07-21 20:24:33
java的主要特性学习总结
2021-11-16 05:46:19
android自定义按钮示例(重写imagebutton控件实现图片按钮)
2021-06-13 07:55:19
C# 多窗口委托通信的实现
2023-01-22 02:21:31
Spring bean为什么需要依赖注入
2022-01-24 11:07:21
Java实现动态数字时钟
2022-05-07 08:56:56
Android 实现把bitmap图片的某一部分的颜色改成其他颜色
2022-12-28 00:12:03
spring mvc实现文件上传并携带其他参数的示例
2023-11-20 11:54:06
Java硬币翻转倍数递增试算实例
2021-09-29 08:39:22
c# AES字节数组加密解密流程及代码实现
2021-12-11 21:44:20
IntelliJ IDEA本地代码提交到github网站不显示与本地不同步问题的解决办法
2022-09-21 10:50:44
详解Java线程同步器CountDownLatch
2023-08-23 18:42:39
ASM的tree api对匿名线程的hook操作详解
2022-07-16 15:03:30
C#检测是否有危险字符的SQL字符串过滤方法
2023-10-11 12:48:48
谈一谈Android内存泄漏问题
2023-01-29 23:23:54
springboot 中整合mybatis多数据源不使用JPA
2023-03-01 08:43:02
如何基于java实现Gauss消元法过程解析
2023-12-15 21:51:08