9.1.5、QQ登陆聊天功能(发文件)
1、需求分析
2、思路分析
3、代码实现
Common:
1) cn.com.agree.qqcommon.MessageType
String MESSAGE_FILE_MESSAGE="8";//文件消息
2) cn.com.agree.qqcommon.Message
private byte[] fileBytes ;
private int len = 0;
private String src ;
private String desc;
QQClient:
1) cn.com.agree.qqclient.QQView.QQView
case "4":
log.debug("请输入要发送的用户(在线):");
getterId = Utility.readString(50);
log.debug("请输入源文件路径(/**):");
String srcPath = Utility.readString(100);
log.debug("请输入目标电脑存储的路径(/**):");
String descPath = Utility.readString(100);
fileClientService.sendFileToOne(userId,getterId,srcPath,descPath);
// System.out.println("发送文件");
break;
2) cn.com.agree.qqclient.service.FileClientService
package cn.com.agree.qqclient.service;
import cn.com.agree.qqcommon.Message;
import cn.com.agree.qqcommon.MessageType;
import cn.com.agree.stream.MyObjectOutputStream;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* @version 1.0
* @ClassName FileClientService
* @Description TODO 类描述
* @date 2024/1/11 4:11 下午
**/
@Slf4j
public class FileClientService {
/**
* 发送文件的方法
* @param senderId
* @param getterId
* @param src
* @param desc
*/
public void sendFileToOne(String senderId,String getterId,String src,String desc){
//构建消息对象
Message message = new Message();
message.setMsgType(MessageType.MESSAGE_FILE_MESSAGE);
message.setSrc(src);
message.setDesc(desc);
message.setSender(senderId);
message.setGetter(getterId);
//将磁盘上的文件读入流中并通过socket进行发送
///Users/andong/agree/socket/src/main/resources/1.jpg
FileInputStream fileInputStream=null;
try {
fileInputStream = new FileInputStream(src);
byte[] fileBytes = new byte[(int)new File(src).length()];
fileInputStream.read(fileBytes);
message.setFileBytes(fileBytes);
log.debug(senderId+" 给 "+getterId+" 发送了"+src+" 到我的电脑的 "+desc+" 路径");
//获取socket进行数据写入
ObjectOutputStream oos = new MyObjectOutputStream(ManageClientConnectServers.getClientConnectServer(senderId).getSocket().getOutputStream());
oos.writeObject(message);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3) cn.com.agree.qqclient.service.ClientConnectServer
case MessageType.MESSAGE_FILE_MESSAGE:
//log.debug("message:{}", message);
log.debug(message.getSender()+" 给 "+message.getGetter()+" 发送了 "+message.getSrc()+" 到我的电脑的 "+message.getDesc()+" 路径");
//进行转发给客户端
ObjectOutputStream oos4= new MyObjectOutputStream(ManageServerConnectClient.getServerConnectClient(message.getGetter()).socket.getOutputStream());
oos4.writeObject(message);
break;
QQServer:
1) cn.com.agree.qqserver.service.ServerConnectClient
case MessageType.MESSAGE_FILE_MESSAGE:
//log.debug("message:{}", message);
log.debug(message.getSender()+" 给 "+message.getGetter()+" 发送了 "+message.getSrc()+" 到我的电脑的 "+message.getDesc()+" 路径");
//进行转发给客户端
ObjectOutputStream oos4= new MyObjectOutputStream(ManageServerConnectClient.getServerConnectClient(message.getGetter()).socket.getOutputStream());
oos4.writeObject(message);
break;
4、效果展示