网络——为什么我的简单java聊天程序只能成功捕获它收到的一些消息?

nfg76nw0  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(167)

我用java创建了一个简单的加密消息传递程序 2 programs . A. server ,传递消息,以及 client 从服务器发送和接收消息的程序。现在我的问题是客户端程序如何侦听传入消息,我想。消息的发送没有问题,并且已经过测试,但是当消息传入时,监听器可能有三分之一的机会正确地解密消息,并且没有错误。
我和我的朋友花了一段时间试图找出原因,我相信这是我们如何创建listner的结果。我将在下面链接listner的代码。它在thred上运行,在while循环上循环,运行将解密消息并将其显示给用户的代码。

package openmsgc1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class ClientReceiver implements Runnable{
    private Socket client;
    public BufferedReader in;
    public PrintWriter out;
    public Encryption e;

    public ClientReceiver(Socket clientSocket) throws IOException {
        this.client = clientSocket;
    }

    @Override
    public void run(){
        in = null;
        out = null;
        String request = null;
        try {

            this.in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            this.out = new PrintWriter(client.getOutputStream());

            while(true){
                request = in.readLine();
                String DecryptedMSG = "";

                if(request!=null){
                    System.out.println("Got to the if statement"); 
                    byte[] decodedmsg = request.getBytes(Charset.forName("ISO-8859-1")); // decodes message
                    try {
                        System.out.println(request);
                        DecryptedMSG = e.decrypt(decodedmsg, e.privateKey); // decrypts message with users private key
                        System.out.println("Past line 55 on thread");
                    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException ex) {
                        Logger.getLogger(ClientReceiver.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }else{
                    System.out.println("No request");
                }
                if(DecryptedMSG.equals(null)==false){
                System.out.println(DecryptedMSG);
                // Outputs message to user
                }

                // System.out.println(request);
            }
        } catch (IOException ex) {
            Logger.getLogger(ClientReceiver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

如果你需要我澄清任何事情,请告诉我。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题