准备工作:
1.在服务端和客户端项目中都建立中间传递对象,implements序列化
public class ContextDemo implements Serializable {
// 0:上线 1:发送信息 2:下线 3:抖窗 4:发送文件
private int type;
private HashSet<String> clients;
private String info;
private String name;
private String time;
private String last;
private ArrayList<Byte> list2;
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public ArrayList<Byte> getList2() {
return list2;
}
public void setList2(ArrayList<Byte> list2) {
this.list2 = list2;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public HashSet<String> getClients() {
return clients;
}
public void setClients(HashSet<String> clients) {
this.clients = clients;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
} 2.服务端实现监听
服务端静态创建一个可以监听客户端连接的serversocket和可以存储在线用户名与socket的Hashmap,服务端开启监听,并在监听到任意客户端的连接时开启一个新的服务端监听线程(将该用户的socket通过构造函数传递给这个线程)
public static ServerSocket ss;
public static HashMap<String, Socket> online;
public static Socket socket;
static {
try {
ss = new ServerSocket(8080);
System.out.println("服务器已开启");
online = new HashMap<String, Socket>();
} catch (IOException e) {
e.printStackTrace();
}
}
public void action() {
try {
while (true) {
Socket s = ss.accept();
System.out.println("服务器正在监听");
new Server_Thread(s).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new Chat_Server().action();
} 线程中定义
(1)发送给全部在线用户的方法,主要是通过创建Hashmap的iterator来实现遍历,获取到每一个在线用户的socket,并用这个用户的socket来建立outputstream进行消息的传递
// 定义发送给全部用户的方法
public void sendtoall(ContextDemo servercontext) {
Collection<Socket> clients = online.values();
Iterator<Socket> iterator = clients.iterator();
ObjectOutputStream oo;
while (iterator.hasNext()) {
Socket socket = iterator.next();
try {
oo = new ObjectOutputStream(socket.getOutputStream());
oo.writeObject(servercontext);
oo.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} (2)发送给指定用户的方法,方法实现与发送给全部用户的方法基本一致,只是需要进行判断,如果选中的用户中包含遍历出来的在线用户,再取socket进行发送
// 定义发送给指定用户的方法
public void sendtothis(ContextDemo servercontext) {
HashSet<String> clients = clientcontext.getClients();
Set<String> oo = online.keySet();
Iterator<String> it = oo.iterator();
//如果用的同一个输出流对象,可能会因前一个未写完而发生错误
ObjectOutputStream ooo;
while (it.hasNext()) {
String name = it.next();
if (clients.contains(name)) {
Socket s = online.get(name);
try {
ooo = new ObjectOutputStream(s.getOutputStream());
ooo.writeObject(servercontext);
ooo.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} 注意:此时应该在其中单独定义一个objectoutputstream,因为写出的时候有时间差!!!此bug耗费10小时寻找!!!!(关掉一个客户端后,另外一个报IOexcption)
线程开始不停地监听从客户端发过来的信息(中间传递对象),并判断type,通过switch语句执行不同的操作
@Override
public void run() {
try {
while (true) {
in = new ObjectInputStream(socket.getInputStream());
clientcontext = (ContextDemo) in.readObject();
// 分析type的种类,来用以判断执行哪种操作
switch (clientcontext.getType()) { 一、注册
界面:
获取到用户输入的用户名密码,进行一系列的判断,与配置文件中的数值进行比对,如果无误则保存当前用户输入的用户名、密码进配置文件,并成功登陆到聊天室界面(通过构造函数传递socket和username),否则则报错
try {
Properties userPro = new Properties();
userPro.load(new FileInputStream("Users.properties"));
String username = usertext.getText();
String passwordFirst = new String(password1.getPassword());
String passwordLast = new String(password2.getPassword());
if (username.length() != 0) {
if (userPro.containsKey(username)) {
JOptionPane.showMessageDialog(getContentPane(), "用户名已经存在!");
} else {
if(passwordFirst.equals(passwordLast)){
if(passwordFirst.length()!=0){
userPro.setProperty(username, passwordFirst);
userPro.store(new FileOutputStream("Users.properties"), "用户名——密码");
//进入聊天界面
Socket socket = new Socket("localhost", 8080);
ChatRoom chatRoom = new ChatRoom(username,socket);
chatRoom.setVisible(true);
setVisible(false);
}else {
JOptionPane.showMessageDialog(getContentPane(), "密码不能为空");
}
}else {
JOptionPane.showMessageDialog(getContentPane(), "两次输入密码不一致");
}
}
} else {
JOptionPane.showMessageDialog(getContentPane(), "用户名不能为空");
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 二、登录
界面:

用户输入用户名和密码,此时通过与项目自带的properties配置文件中的内容进行比对,如果有记录,则可以进入到聊天室(通过设置了每个testfield和登录按钮的keypressed事件,可通过检测按下回车按钮进入),若没有,则要求进入注册界面。
注意:如可以进入到聊天室界面,需要将此时新建的socket和用户名通过聊天室界面的构造函数传给聊天室。
try {
Properties properties = new Properties();
properties.load(new FileInputStream("Users.properties"));
String usernameString = textusername.getText();
String pasString = new String(password1.getPassword());
if(properties.containsKey(usernameString)){
if(properties.getProperty(usernameString).equals(pasString)){
Socket socket = new Socket("localhost", 8080);
ChatRoom chatRoom = new ChatRoom(usernameString,socket);
chatRoom.setVisible(true);
setVisible(false);
}else {
JOptionPane.showMessageDialog(getContentPane(), "密码输入错误");
}
}else {
JOptionPane.showMessageDialog(getContentPane(), "该用户名不存在");
} 三、聊天室主界面
界面:

1.本用户上线报告服务器+服务器将该用户上线信息发送给全部用户
(1)客户端的构造函数中,将本用户的socket,用户名,当前系统时间,中间传递对象的类型(上线类型为0),封装进中间传递对象并通过socket的outputstream发送给服务端,并开启客户端线程进行监控服务端传过来的信息
// 上线则汇报给服务器
try {
out = new ObjectOutputStream(socket.getOutputStream());
// 创建传输对象
ContextDemo clientcontext = new ContextDemo();
clientcontext.setType(0);
clientcontext.setName(username);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
clientcontext.setTime(sdf.format(new Date()));
// 发送给服务端
out.writeObject(clientcontext);
out.flush();
// 开启客户端线程
new Client_Thread().start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 客户端线程开始监听
@Override
public void run() {
try {
while (true) {
System.out.println("客户端线程启动");
in = new ObjectInputStream(socket.getInputStream());
final ContextDemo servercontext = (ContextDemo) in.readObject();
switch (servercontext.getType()) { (2)服务端得到该用户的中间传递对象,判断出执行上线操作,执行相应的switch语句,将用户名与socket存入hashmap,并创建当前用户的上线信息,对象类型type,以及在线用户名的集合封装进对象发送给所有的在线用户
// 上线
case 0:
// 添加在线用户进online
{
online.put(clientcontext.getName(), socket);
ContextDemo serverContext = new ContextDemo();
// 将用户上线信息发送给各客户端
serverContext.setType(0);
serverContext.setInfo(clientcontext.getTime() + " " + clientcontext.getName() + " 上线啦!");
// 将在线用户用户名全部发给客户端
HashSet<String> set = new HashSet<String>();
set.addAll(online.keySet());
serverContext.setClients(set);
sendtoall(serverContext);
break;
} (3)客户端监听到信息,判断出为上下线更新操作,先清空在线列表集合,在将所要取得的各种信息从对象中取得,并获取到在线人数集合中数目以实现在线人数显示,并将上线消息显示在testArea中
case 0:
// 重新装填容器
{
// 清空容器
online.clear();
HashSet<String> set = servercontext.getClients();
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
if (username.equals(name)) {
online.add(name + "(本机)");
} else {
online.add(name);
}
}
// 显示在list中
listmodel = new UUListModel(online);
count = listmodel.getSize();
list.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "在线用户:"+count+"人",
TitledBorder.LEADING, TitledBorder.TOP, null, new Color(255, 0, 0)));
list.setModel(listmodel);
docs.insertString(docs.getLength(), servercontext.getInfo() + "\n", attrset);
break;
} 2.发送消息
(1)客户端获取到list中选中的用户(若不选则为群发),将该选中用户、自己的用户名、时间、要发送的信息等内容封装进对象,设置type为1(发送信息识别码),将对象传递给服务器,在自己的聊天界面添加聊天的内容,随后清空list表的选中状态以及发送框的内容(发送按钮与回车键均可发送消息)
// 发送按钮
JButton btnNewButton = new JButton("\u53D1\u9001");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
List selected = list.getSelectedValuesList();
String info = textArea_1.getText();
if (selected.size() < 1) {
// 在客户端中,容器online中本机的名字后面多加了字符,所以在客户端不能与hashmap中的key匹配,所以本机收不到本机传来的信息
selected = online;
}
if (info.equals("")) {
JOptionPane.showMessageDialog(getContentPane(), "不能发送空信息");
return;
}
ContextDemo clientcontext = new ContextDemo();
clientcontext.setInfo(info);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
clientcontext.setTime(time);
clientcontext.setType(1);// 发信息
clientcontext.setName(username);
HashSet<String> people = new HashSet<String>();
people.addAll(selected);
clientcontext.setClients(people);
// 清空发送页面
textArea_1.setText("");
// 发送界面获得焦点
textArea_1.requestFocus();
// 列表消除选中状态
list.clearSelection();
try {
out = new ObjectOutputStream(ChatRoom.socket.getOutputStream());
out.writeObject(clientcontext);
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
docs.insertString(docs.getLength(), time + " " + "我对"+selected+"说:\n" + info + "\n", attrset);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}); (2)服务器判断出为发送消息后,将得到的信息、时间等消息进行封装,再通过发送给指定用户的方法将封装好的对象传递给指定的用户
// 发信息
case 1: {
ContextDemo servercontext = new ContextDemo();
servercontext.setType(1);
servercontext.setName(clientcontext.getName());
servercontext.setInfo(clientcontext.getInfo());
servercontext.setTime(clientcontext.getTime());
sendtothis(servercontext);
break;
} (3)指定的客户端收到对象后判断出了是要进行发送消息的操作,解封对象,取得消息等信息,在消息窗口显示
// 发信息
case 1: {
String info = servercontext.getInfo();
String time = servercontext.getTime();
docs.insertString(docs.getLength(),
time + " " + servercontext.getName() + "对我说:\n" + info + "\n", attrset);
break;
} 3.下线
(1)聊天室页面添加窗口关闭的监听事件,在其后弹出对话框确定是否退出,若退出则设置type为2(下线识别码)、时间等信息封装进对象发送给服务器
// 下线操作
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(getContentPane(),"您确定要离开聊天室");
if (result == 0) {
ContextDemo clientcontext = new ContextDemo();
clientcontext.setType(2);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
clientcontext.setTime(sdf.format(new Date()));
clientcontext.setName(username);
try {
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(clientcontext);
out.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}); (2)服务器判断为是下线操作后,首先建立服务端对象,设置type为2,用当前用户传递过来的socket传递此对象给即将下线的客户端批准其下线,随后用下线用户的用户名在Hashmap中删除此用户,随后新建另一服务端对象,封装下线的信息、时间、当前在线用户名等内容发送给其余所有在线的客户端,让他们执行上下线更新操作,并在case的最后用return退出whlie(true)循环,在finally中关闭掉输入输出流对象与socket对象,意在此客户端与服务端的线程关闭
// 下线
case 2: {
// 通知请求下线客户端,批准下线
ContextDemo servercontext1 = new ContextDemo();
servercontext1.setType(2);
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(servercontext1);
out.flush();//需要时间
// 刷新在线hashmap
online.remove(clientcontext.getName());
// 通知其他在线用户,该用户已下线
ContextDemo servercontext2 = new ContextDemo();
servercontext2.setType(0);
servercontext2.setInfo(clientcontext.getTime() + " " + clientcontext.getName() + "用户已下线 ");
HashSet<String> set = new HashSet<String>();
set.addAll(online.keySet());
servercontext2.setClients(set);
sendtoall(servercontext2);
// 退出当前循环,不再监听该客户端传来的信息
return;
} (3)
1)即将下线的客户端接收到对象后,判断出是执行下线操作,用return退出while(true),并在finally中关闭掉socket与输入输出流对象,并用System.exit(0)退出虚拟机断线
// 下线
case 2:{
return;
} 2)其余在线客户端接收到对象,判断是要进行上下线操作,所以执行与上线更新时一样的操作
// 上下线刷新操作
case 0:
// 重新装填容器
{
// 清空容器
online.clear();
HashSet<String> set = servercontext.getClients();
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
if (username.equals(name)) {
online.add(name + "(本机)");
} else {
online.add(name);
}
}
// 显示在list中
listmodel = new UUListModel(online);
count = listmodel.getSize();
list.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "在线用户:"+count+"人",
TitledBorder.LEADING, TitledBorder.TOP, null, new Color(255, 0, 0)));
list.setModel(listmodel);
docs.insertString(docs.getLength(), servercontext.getInfo() + "\n", attrset);
break;
} 4.抖窗
(1)客户端将列表中得到的用户名封装进对象,设置type为3,再将时间等信息封装进对象,将对象发送给服务端
btnShakeFrame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
List selected = list.getSelectedValuesList();
if (selected.size() < 1) {
// 在客户端中,容器online中本机的名字后面多加了字符,所以在客户端不能与hashmap中的key匹配,所以本机收不到本机传来的信息
selected = online;
}
ContextDemo clientcontext = new ContextDemo();
clientcontext.setType(3);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
clientcontext.setTime(time);
clientcontext.setName(username);
HashSet<String> set = new HashSet<String>();
set.addAll(selected);
clientcontext.setClients(set);
// 列表消除选中状态
list.clearSelection();
try {
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(clientcontext);
out.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
docs.insertString(docs.getLength(), time + "您发送了一个屏幕抖动\n", attrset);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}); (2)服务端判断出是要进行抖窗操作后,封装有用的信息进对象,并通过发送给指定用户方法进行发送
// 抖窗
case 3: {
ContextDemo servercontext = new ContextDemo();
servercontext.setType(3);
servercontext.setInfo(clientcontext.getTime() + " " + clientcontext.getName() + "对你抖了一下屏 \n");
sendtothis(servercontext);
break;
} (3)指定的客户端判断要进行抖屏,先解封有用的信息进消息显示窗口,然后再调用封装好的抖屏方法进行抖屏操作
// 抖窗
case 3: {
String info = servercontext.getInfo();
docs.insertString(docs.getLength(), info, attrset);
shakeFrame();
break;
}public void shakeFrame() {
int x = ChatRoom.this.getX();
int y = ChatRoom.this.getY();
for (int i = 0; i < 20; i++) {
if ((i & 1) == 0) {
x += 8;
y += 8;
} else {
x -= 8;
y -= 8;
}
ChatRoom.this.setLocation(x, y);
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
} 5.发送文件
(1)客户端先获取到想要发送文件给哪个用户的用户名,随后弹出文件选择框,构建文件的抽象路径,并得到后缀名,其后通过文件的输入流将所得到的文件一个字节一个字节的读入到Arraylist<byte>集合中,将后缀名保存到一个字符串中,将这些与其他有用的信息一起封装进对象,将对象发送给服务器
btnSendFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
List selected = list.getSelectedValuesList();
if (selected.size() < 1) {
JOptionPane.showMessageDialog(getContentPane(), "必须选择一名用户");
return;
}
if (selected.toString().contains(username+"(本机)")) {
JOptionPane.showMessageDialog(getContentPane(), "不能向自己发送文件");
return;
}
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("选择文件框");
chooser.showDialog(getContentPane(), "选择");
//判断是否拿到文件
if(chooser.getSelectedFile()!=null){
path = chooser.getSelectedFile().getPath();
file = new File(path);
//获取文件的后缀名
int i =file.getName().indexOf(".");
last = file.getName().substring(i);
//判断文件是否为空
if(file.length()==0){
JOptionPane.showMessageDialog(getContentPane(), "文件为空,不能传送");
return;
}
}
ContextDemo clientcontext = new ContextDemo();
//发送文件(基础工作)
clientcontext.setType(4);
//保存后缀名
clientcontext.setLast(last);
clientcontext.setName(username);
HashSet<String> set = new HashSet<String>();
set.addAll(selected);
clientcontext.setClients(set);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
clientcontext.setTime(time);
//发送文件(文件部分操作)
list2 = new ArrayList<Byte>();
try {
input = new FileInputStream(file);
int result = -1;
while((result = input.read()) != -1)
{
list2.add((byte)result);
}
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
try {
if(input != null)
{
input.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
clientcontext.setList2(list2);
// 列表消除选中状态
list.clearSelection();
//发送给服务端
try {
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(clientcontext);
out.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
docs.insertString(docs.getLength(), time + "您发送了一个文件\n", attrset);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}); (2)服务端判断出是要进行文件的发送操作,将所有有用的信息封装进对象发送给指定的用户
// 发送文件
case 4: {
ContextDemo servercontext = new ContextDemo();
servercontext.setList2(clientcontext.getList2());
servercontext.setLast(clientcontext.getLast());
servercontext.setInfo(clientcontext.getTime() + " " + clientcontext.getName() + "对你发送了一个文件\n");
servercontext.setType(4);
sendtothis(servercontext);
break;
} (3)指定客户端收到对象后,先将字节集合解封出来,用iterator将字节写入一个字节数组,再通过缓冲字节流读入字节,通过解封出来的后缀名构造好新的文件后,通过缓冲字节流写入文件,并接收到需要的信息显示在消息窗口中
//接收到文件
case 4:
{
ArrayList<Byte> list3 = new ArrayList<Byte>();
list3 = servercontext.getList2();
Iterator<Byte> it = list3.iterator();
byte[] dedao = new byte[10000000];
int i = 0;
while(it.hasNext()){
dedao[i] = it.next();
i++;
}
ii = new ByteArrayInputStream(dedao);
inputStream = new BufferedInputStream(ii,10000);
//获取后缀名
String thLast = servercontext.getLast();
output = new FileOutputStream("sourse/dedao"+thLast);
outputStream = new BufferedOutputStream(output,10000);
byte[] b = new byte[10000];//暂存读取的字节内容
int result = -1;
while((result = inputStream.read(b)) != -1)
{
outputStream.write(b, 0, result);
}
output.flush();
String info = servercontext.getInfo();
docs.insertString(docs.getLength(), info, attrset);
break;
}