简体   繁体   English

Java套接字:如何仅在DataInputStream中显示消息一次

[英]Java sockets: How to display message in DataInputStream only once

I have written a class which already allows me to connect 2 devices using sockets, I also implemented the ability to let each other send a message. 我编写了一个类,该类已经允许我使用套接字连接2个设备,并且还实现了允许彼此发送消息的功能。 I get the received message with a DataInputStream which constantly checks for a message in a while(true){} loop. 我收到了带有DataInputStream的接收到的消息,该消息会在while(true){}循环中不断检查消息。 I log the messages, but they spam the whole console. 我记录了这些消息,但它们对整个控制台都是垃圾邮件。 So I added a variable called lastMsg which checks whether the current message is the last received message, if it is the case, it will not print the message, so the message will only be logged once. 因此,我添加了一个名为lastMsg的变量,该变量检查当前消息是否为最后收到的消息,如果是这种情况,它将不会打印该消息,因此该消息将仅记录一次。 The problem is that when a user sends two identical messages, only the first one will obviously be logged. 问题在于,当用户发送两条相同的消息时,显然只会记录第一条消息。

So is there an other way to check if a message is either send two times, or the message is just the same one sent some seconds ago? 因此,还有另一种方法可以检查消息是否发送了两次,或者消息是否与几秒钟前发送的消息相同?

My code to check the received message: 我的代码来检查收到的消息:

 public void run() {
            Socket other = new Socket();
            try {
            other.connect(new InetSocketAddress("xxxxxx", xxxx), 1000);
            log("Connected to host");
            while (true) {

                DataInputStream in = new DataInputStream(other.getInputStream());
                String msg = in.readUTF();
                if(!lastClientMsg.equals(msg)){
                    log("[HOST-MSG] "+msg);
                    lastClientMsg = msg;
                }


            }
                } catch (IOException e) {
                log("Error at creating client: "+e.toString());
            }

        }

Try using a collection object to store last 20 messages. 尝试使用收集对象存储最后20条消息。 ArrayList will do fine. ArrayList会很好。 check last 20 messages and remove the first one in every new message and add the new one to the collection. 检查最后20条消息,并删除每条新消息中的第一条,然后将新消息添加到集合中。

Good Luck. 祝好运。

Using the DataInputStream.readUTF() method should move the message from the input buffer to the string variable, but the buffer is not being cleared for some reason. 使用DataInputStream.readUTF()方法应将消息从输入缓冲区移到字符串变量,但是由于某些原因不能清除缓冲区。 A few tips: 一些提示:

  • Try moving your DataInputStream declaration outside of the while loop. 尝试将您的DataInputStream声明移到while循环之外。 Declaring it every time you check for a message could be your problem. 每次检查消息时都声明它可能是您的问题。
  • Make sure that your code sending the message only sends it once. 确保发送消息的代码仅发送一次。 If by any chance it is being sent in a loop it'll clog up your input stream. 如果有任何机会将其循环发送,它将阻塞您的输入流。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM