带有文件传输和混合加密的java聊天客户端服务器
我正在尝试实现一个聊天客户端服务器(在本地),它允许交换文本和文件。我利用java.security
和java.crypto
来实现混合加密(以及工具Swing)。
我以序列化的方式交换文本(使用ObjectInputStream
和ObjectOutputStream
),在消息中插入byte[]
格式的文本(这是我创建的一个对象,在socket之间有效地交换):
import java.io.Serializable;
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
byte[] data;
Message(byte[] data){
this.data = data;
}
byte[] getData(){
return data;
}
}
聊天很好,直到我只交换Message
。现在我正在尝试实现文件传输(首先我尝试实现从服务器到客户机的文件传输,没有加密),因此我用FileChoser获取了一个文件“selectedFile”,并通过ObjectOutputStream
的方法writeObject(selectedFile)
将其发送到客户机。在客户端,我识别出到达的对象是File
还是Message
带有:
class ListenFromServer extends Thread{
public void run(){
while(true){
try{
if((Message.class.isInstance(sInput.readObject()))==true){ //I verify if the recived object belongs to Message class
m=(Message) sInput.readObject();//sInput is an instance of ObjectInputStream class, connected to client socket's InputeStream
decryptMessage(m.getData()); //function that decrypts the content of m and inserts the result in a String that after I append in a text area
}
else
{
File recivedFile= (File) sInput.readObject();
File saveFile=new File(path+"/"+ recivedFile.getName());
save(recivedFile,saveFile);//function that insert the recived file in a specific folder
System.out.println("file ricevuto");
}
} catch (ClassNotFoundException ex) {
System.out.println("INFO: Classe non trovata durante la lettura dell'oggetto Messaggio: " + ex.getMessage() + "\n");
} catch(IOException e){
System.out.println("Connection closed");
break;
}
catch(NullPointerException ne){
ne.printStackTrace();
ne.getCause();
System.out.println("Errore"+ ne.getMessage());
}
问题是,客户端只需点击两次服务器的“sendFile”按钮即可接收文件,而且现在这个问题还涉及到向客户端发送文本的操作,因为客户端只在我发送两次时接收Message
对象(我使用两种不同的方法发送Message
对象和File
对象)
当我删除指令时,不会出现此问题:
if((Message.class.isInstance(sInput.readObject()))==true){
...
}
我问您如何克服这个问题,或者是否有更好的方法来区分接收中的文件和消息对象
# 1 楼答案
你实际上是在按顺序读两个物体,而不是一个
这是读取对象的命令。按顺序给出两次,这就是读取不同对象的两个请求
要解决这个问题,只需读取对象一次,测试对象的类型,并在适当时强制转换: