我正在尝试实现允许交换文本和文件的聊天客户端-服务器(在本地)。我利用 java.security
和 java.crypto
来实现混合加密(和工具 Swing)。
我以序列化的方式交换文本(使用 ObjectInputStream
和 ObjectOutputStream
),将它插入(在我用适当的函数加密之后)到 byte[]
消息中的格式(这是我创建的对象,在套接字之间有效交换):
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”按钮就可以收到文件,而且现在这个问题还涉及到向客户端发送文本的 Action ,因为客户端只有在我发送了两次(我使用两种不同的方法发送一个 Message
对象和一个 File
对象)。
我去掉指令就不会出现这个问题:
if((Message.class.isInstance(sInput.readObject()))==true){
...
}
我问你如何克服这个问题,或者有没有更好的方法来区分接收中的文件和消息对象。
最佳答案
您实际上是在依次读取两个对象,而不是一个。
sInput.readObject()
这是一个读取对象的命令。您按顺序给出两次,因此这是读取不同对象的两个请求。
要解决这个问题,只需读取对象一次,测试对象的类型,并在适当的时候进行转换:
Object inputObject = sInput.readObject(); // Read the object once
if (inputObject instanceof Message) { // If the object is a message
Message m = (Message) inputObject; // cast as a Message
... // use the Message m
} else if (inputObject instanceof File) { // else if it's a file
File f = (File) inputObject; // cast as a File
... // use the File f
}
关于java - 使用文件传输和混合加密技术聊天客户端-服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48789489/