java聊天室的实现代码

 更新时间:2020年03月31日 16:41:16   作者:北漂程序员-阿力  
这篇文章主要为大家详细介绍了java聊天室的实现代码,一个多客户端聊天室,支持多客户端聊天,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java实现聊天室的具体代码,供大家参考,具体内容如下

聊天室界面:

源码:

public class ClientFrame extends Frame {

 private TextField textFieldContent = new TextField();
 private TextArea textAreaContent = new TextArea();
 private Socket socket = null;
 private OutputStream out = null;
 private DataOutputStream dos = null;
 private InputStream in = null;
 private DataInputStream dis = null;
 private boolean flag = false;

 /**
 * 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午9:19:51 功能:启动客户端程序
 * 
 * @param args
 */
 public static void main(String[] args) {
 new ClientFrame().init();
 }

 /**
 * 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午9:20:43 功能:对窗口进行初始化
 */
 private void init() {
 this.setSize(300, 300);
 setLocation(250, 150);
 setVisible(true);
 setTitle("WeChatRoom");

 // 添加控件
 this.add(textAreaContent);
 this.add(textFieldContent, BorderLayout.SOUTH);
 textAreaContent.setFocusable(false);
 pack();

 // 关闭事件
 addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent e) {
  System.out.println("用户试图关闭窗口");
  disconnect();
  System.exit(0);
  }

 });
 // textFieldContent添加回车事件
 textFieldContent.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
  onClickEnter();
  }
 });

 // 建立连接
 connect();
 new Thread(new ReciveMessage()).start();
 }

 private class ReciveMessage implements Runnable {
 @Override
 public void run() {
  flag = true;
  try {
  while (flag) {
   String message = dis.readUTF();
   textAreaContent.append(message + "\n");
  }
  } catch (EOFException e) {
  flag = false;
  System.out.println("客户端已关闭");
  // e.printStackTrace();
  } catch (SocketException e) {
  flag = false;
  System.out.println("客户端已关闭");
  // e.printStackTrace();
  } catch (IOException e) {
  flag = false;
  System.out.println("接受消息失败");
  e.printStackTrace();
  }
 }

 }

 /**
 * 功能:当点击回车时出发的事件 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午9:49:30
 */
 private void onClickEnter() {
 String message = textFieldContent.getText().trim();
 if (message != null && !message.equals("")) {
  String time = new SimpleDateFormat("h:m:s").format(new Date());
  textAreaContent.append(time + "\n" + message + "\n");
  textFieldContent.setText("");
  sendMessageToServer(message);
 }
 }

 /**
 * 功能:给服务器发送消息 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:13:48
 * 
 * @param message
 */
 private void sendMessageToServer(String message) {
 try {
  dos.writeUTF(message);
  dos.flush();
 } catch (IOException e) {
  System.out.println("发送消息失败");
  e.printStackTrace();
 }
 }

 /**
 * 功能:申请socket链接 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:00:38
 */
 private void connect() {
 try {
  socket = new Socket("localhost", 8888);
  out = socket.getOutputStream();
  dos = new DataOutputStream(out);
  in = socket.getInputStream();
  dis = new DataInputStream(in);
 } catch (UnknownHostException e) {
  System.out.println("申请链接失败");
  e.printStackTrace();
 } catch (IOException e) {
  System.out.println("申请链接失败");
  e.printStackTrace();
 }
 }

 /**
 * 功能:关闭流和链接 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:01:32
 */
 private void disconnect() {
 flag = false;
 if (dos != null) {
  try {
  dos.close();
  } catch (IOException e) {
  System.out.println("dos关闭失败");
  e.printStackTrace();
  }
 }
 if (out != null) {
  try {
  out.close();
  } catch (IOException e) {
  System.out.println("dos关闭失败");
  e.printStackTrace();
  }
 }
 if (socket != null) {
  try {
  socket.close();
  } catch (IOException e) {
  System.out.println("socket关闭失败");
  e.printStackTrace();
  }
  ;
 }
 }

}
package com.chat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

public class ChatServer {

 private List<Client> clients = new ArrayList<>();

 /**
 * 功能:启动ChatSever 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:26:41
 * 
 * @param args
 */
 public static void main(String[] args) {
 new ChatServer().init();
 }

 /**
 * 功能:对chatserver初始化 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:27:09
 */
 private void init() {
 System.out.println("服务器已开启");
 // BindException

 ServerSocket ss = null;
 Socket socket = null;
 try {
  ss = new ServerSocket(8888);
 } catch (BindException e) {
  System.out.println("端口已被占用");
  e.printStackTrace();
 } catch (IOException e1) {
  e1.printStackTrace();
 }
 try {
  Client client = null;
  while (true) {
  socket = ss.accept();
  System.out.println("客户驾到");
  client = new Client(socket);
  clients.add(client);
  new Thread(client).start();
  }
 } catch (IOException e) {
  e.printStackTrace();
 }
 }

 private class Client implements Runnable {
 private Socket socket = null;
 InputStream in = null;
 DataInputStream din = null;
 OutputStream out = null;
 DataOutputStream dos = null;
 boolean flag = true;

 public Client(Socket socket) {
  this.socket = socket;
  try {
  in = socket.getInputStream();
  din = new DataInputStream(in);
  } catch (IOException e) {
  System.out.println("接受消息失败");
  e.printStackTrace();
  }

 }

 public void run() {

  String message;
  try {
  while (flag) {
   message = din.readUTF();
   // System.out.println("客户说:" + message);
   forwordToAllClients(message);
  }
  } catch (SocketException e) {
  flag = false;
  System.out.println("客户下线");
  clients.remove(this);
  // e.printStackTrace();
  } catch (EOFException e) {
  flag = false;
  System.out.println("客户下线");
  clients.remove(this);
  // e.printStackTrace();
  } catch (IOException e) {
  flag = false;
  System.out.println("接受消息失败");
  clients.remove(this);
  e.printStackTrace();
  }

  if (din != null) {
  try {
   din.close();
  } catch (IOException e) {
   System.out.println("din关闭失败");
   e.printStackTrace();
  }
  }
  if (in != null) {
  try {
   in.close();
  } catch (IOException e) {
   System.out.println("din关闭失败");
   e.printStackTrace();
  }
  }
  if (socket != null) {
  try {
   socket.close();
  } catch (IOException e) {
   System.out.println("din关闭失败");
   e.printStackTrace();
  }
  }

 }

 /**
  * 功能:转发给所有客户端 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午11:11:59
  * 
  * @param message
  * @throws IOException
  */
 private void forwordToAllClients(String message) throws IOException {
  for (Client c : clients) {
  if (c != this) {
   out = c.socket.getOutputStream();
   dos = new DataOutputStream(out);
   forwordToClient(message);
  }
  }
 }

 /**
  * 功能:发送给一个客户端 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午11:16:12
  * 
  * @throws IOException
  */
 private void forwordToClient(String message) throws IOException {
  dos.writeUTF(message);
  dos.flush();
  System.out.println("转发成功!");
 }

 }
}

源码下载:java聊天室代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 详解Java8 StreamAPI中的map()方法

    详解Java8 StreamAPI中的map()方法

    Stream API 是Java8中新加入的功能,这篇文章主要带大家了解一下 Stream API 中的 map() 方法的使用,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-04-04
  • SpringBoot实现整合微信支付方法详解

    SpringBoot实现整合微信支付方法详解

    这篇文章主要介绍了SpringBoot实现整合微信支付的过程详解,文中的示例代码对我们的工作或学习有一定的帮助,感兴趣的小伙伴可以跟随小编学习一下
    2021-12-12
  • 使用Spring Boot+MyBatis框架做查询操作的示例代码

    使用Spring Boot+MyBatis框架做查询操作的示例代码

    这篇文章主要介绍了使用Spring Boot+MyBatis框架做查询操作的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-10-10
  • Java Web项目部署在Tomcat运行出错与解决方法示例

    Java Web项目部署在Tomcat运行出错与解决方法示例

    这篇文章主要介绍了Java Web项目部署在Tomcat运行出错与解决方法,结合具体实例形式分析了Java Web项目部署在Tomcat过程中由于xml配置文件导致的错误问题常见提示与解决方法,需要的朋友可以参考下
    2017-03-03
  • Spring MVC实现mysql数据库增删改查完整实例

    Spring MVC实现mysql数据库增删改查完整实例

    这篇文章主要介绍了Spring MVC实现mysql数据库增删改查完整实例,从创建一个web项目开始,分享了项目结构以及具体Java代码和前端页面等相关内容,具有一定借鉴价值,需要的朋友可以了解下。
    2017-12-12
  • spring-data-jpa使用自定义repository来实现原生sql

    spring-data-jpa使用自定义repository来实现原生sql

    这篇文章主要介绍了在spring-data-jpa中使用自定义repository来实现原生sql,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • mybatis-plus 批量插入示例代码

    mybatis-plus 批量插入示例代码

    正常我们使用mybatis-plus插入的时候,首先想到的是saveBatch方法,不过看了下打印出来的sql和底层代码,才发现它并不是真正的批量插入这篇文章主要介绍了mybatis-plus 批量插入示例,需要的朋友可以参考下
    2023-07-07
  • springboot整合JSR303校验功能实现代码

    springboot整合JSR303校验功能实现代码

    这篇文章主要介绍了springboot整合JSR303校验功能实现,JSR303校验方法有统一校验的需求,统一校验实现以及分组校验,本文结合实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2023-01-01
  • Spring boot外部配置(配置中心化)详解

    Spring boot外部配置(配置中心化)详解

    这篇文章主要给大家介绍了关于Spring boot外部配置(配置中心化)的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2017-12-12
  • 简单操作实现Java jsp servlet文件上传过程解析

    简单操作实现Java jsp servlet文件上传过程解析

    这篇文章主要介绍了简单操作实现Java jsp servlet文件上传过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10

最新评论