目 录
1.聊天室项目需求,必须完成的功能点:
- 用户名登录注册(判断有没有重复用户名,可设置ip和端口)
- 上下线提醒
- 在线列表
- 私聊
- 公聊
- 发送文字,文件。
- 聊天记录 保存 查询 删除。
- 下线
2.两个独立的项目如何放在同一个窗口中运行
注意:客户端和服务端是两个独立的项目,但是为了方便,可以放在同一个窗口中!然后将下列代码分包放入并且执行即可!
新建一个空项目Empty Project ---> next 然后给空项目命名 ---> finish
然后弹出下面的窗口,选择Modules ---> 加号 ---> New Moudule ---> ok
然后继续点加号,创建客户端和服务端的项目,下图一创建好,然后点击 ok
最后整个项目的布置是这个样子的
3.服务端代码如下:
定义发送接收相关内容的ChatMsgBean类:
import java.io.Serializable;
public class ChatMsgBean implements Serializable {
private static final long serialVersionUID = 1L;
public String reciver; //接收者
public String sender; //发送者
public String content; //发送内容
public long time; //时间
public int msgType; //消息标志
public String fileName; //文件名
public long fileLength; //文件长度
public byte[] fileData; //文件字节
public ChatMsgBean(String reciver, String sender, String content, long time, int msgType) {
this.reciver = reciver;
this.sender = sender;
this.content = content;
this.time = time;
this.msgType = msgType;
}
public ChatMsgBean(String reciver, String sender, String content, long time, int msgType, String fileName, long fileLength, byte[] fileData) {
this.reciver = reciver;
this.sender = sender;
this.content = content;
this.time = time;
this.msgType = msgType;
this.fileName = fileName;
this.fileLength = fileLength;
this.fileData = fileData;
}
}
输入输出流的工具类InputAndOutputUtil:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class InputAndOutputUtil {
public InputAndOutputUtil() {
}
public static byte[] readFile(String path) {
File file = new File(path);
byte[] datas = null;
if (!file.exists()) {
datas = null;
} else {
try {
//读文件
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[1048576];
boolean var6 = false;
int len;
while((len = fis.read(data)) > 0) {
baos.write(data, 0, len);
}
datas = baos.toByteArray();
baos.flush();
baos.close();
fis.close();
} catch (Exception var7) {
var7.printStackTrace();
}
}
return datas;
}
//写文件
public static boolean writeFile(String path, byte[] datas) {
try {
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
fos.write(datas);
fos.flush();
fos.close();