java TCP套接字消息中断

发布于 2024-12-06 16:50:15 字数 1453 浏览 1 评论 0原文

我有一个java客户端-服务器应用程序,两者都使用包含发送/接收消息的相同连接类。 由于某种原因,我发送的一些消息以格式错误的顺序接收:

这是一些消息的代码

//set up
_in = new BufferedReader(new InputStreamReader(this._socket.getInputStream()));
_out = new BufferedWriter(new OutputStreamWriter(this._socket.getOutputStream()));
this._socket.setSoTimeout(S_TIMEOUT);


public synchronized boolean send(String message){
    try {
        _out.write(message);
        _out.write(Connection.DELIMITER);
        _out.flush();
        return true;
    } catch (IOException e) {
    }
    return false;
}


public String receive(){
    int c;
    try {
        String message = "";
        System.out.println("Getting message:");
        c = _in.read();
        while(c != -1 && c != Connection.DELIMITER) {
            message += (char) c;
            c = _in.read();
        }
        if (c == -1) {
            return null;
        }
        return message;
    } catch (IOException e) { }
    return null;
}

,例如“new_order”可能会返回“ew_ord”。 一些字符丢失,另一些则单独发送。这看起来很奇怪,因为它的 TCP

可能是与编码相关的问题吗?

分隔符为 (char) 0 套接字超时为 20000(即 20 秒)。每 10 秒我发送一条空消息以确保套接字不会关闭

编辑: 虽然它是使用扫描仪解决的,但我必须说,原始代码在很长一段时间内(几周)对于许多消息/各种机器都可以正常工作,然后突然无法在一台特定机器(其他机器)上处理一条特定消息消息处理得很好)。我已经在java中多次完成了套接字数据传输,并且编写了许多读/写方法来处理套接字。这是我第一次遇到这种情况。

虽然在原始代码中我设置了编码(在发布的代码中我没有),但我相信问题与编码相关。有一次,收到的消息每隔一个字符就缺失一次。后来我对其进行了一些更改,并且消息的第一个/第二个字符在单独的消息中收到。根据我的理解,这要么是编码问题,要么是消息发送者计算机上运行的某些防火墙/其他安全程序决定过滤传出数据包。

i have a java client-server app in java, both using the same connection class that contains both send/receive messages.
for some reason, some of the messages i send are received in a malformed order:

here's the code

//set up
_in = new BufferedReader(new InputStreamReader(this._socket.getInputStream()));
_out = new BufferedWriter(new OutputStreamWriter(this._socket.getOutputStream()));
this._socket.setSoTimeout(S_TIMEOUT);


public synchronized boolean send(String message){
    try {
        _out.write(message);
        _out.write(Connection.DELIMITER);
        _out.flush();
        return true;
    } catch (IOException e) {
    }
    return false;
}


public String receive(){
    int c;
    try {
        String message = "";
        System.out.println("Getting message:");
        c = _in.read();
        while(c != -1 && c != Connection.DELIMITER) {
            message += (char) c;
            c = _in.read();
        }
        if (c == -1) {
            return null;
        }
        return message;
    } catch (IOException e) { }
    return null;
}

some messages, for example "new_order" will might return with "ew_ord".
some characters are lost, others are sent separately. this seems odd as its TCP

could this be an encoding related issue?

Delimiter is (char) 0
socket timeout is 20000 (ie 20 senconds). every 10 seconds i send an empty message to make sure socket does not close

EDIT:
although it was solved using the Scanner, i must say that the original code worked fine for many messages/various machines for a very long time (a few weeks), and then suddenly failed to work with one specific message on one specific machine (other messages went through just fine). i've done socket data transfer in java MANY times and i've written many read/write methods to handle the sockets. it's the first time i ran into this.

although in the original code i set the encoding (in the posted code i didn't), i believe that the problem was encoding related. at one point, the message that was received had every second character missing. afterwards i changed it a bit, and the first/second character of the message were received in a separate message. from my understanding, it's either an encoding issue or some firewall/other security program that was running on the message sender machine, that decided to filter outgoing packets.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清君侧 2024-12-13 16:50:15

尝试用扫描仪替换您的接收器,让它为您完成工作。

// in your setup
Scanner sc = new Scanner(_in).useDelimiter(Connection.DELIMETER);

public String receive() {
    try {
        return sc.next();
    } catch(IOException e) {
        return "";
    }

}

Try replacing your receive with a Scanner and let it do the work for you.

// in your setup
Scanner sc = new Scanner(_in).useDelimiter(Connection.DELIMETER);

public String receive() {
    try {
        return sc.next();
    } catch(IOException e) {
        return "";
    }

}
记忆里有你的影子 2024-12-13 16:50:15

对于初学者,我会确保您在这些 catch 块中打印异常。

然后,您使用平台默认编码将字符转换为字节。如果这两个进程在不同的计算机上运行,​​则它们可能使用不同的编码。我会确保您在设置读取器和写入器时指定编码。

For starters, I would make sure you're printing exceptions in those catch blocks.

Then, you're using the platform default encoding for converting characters to bytes. If these two processes are running on different machines, it's possible they're using different encodings. I would make sure you're specifying an encoding when you set up the Reader and Writer.

挖鼻大婶 2024-12-13 16:50:15

您可以使用 UTF 编码来获取完整的消息字符串。

您可以尝试此代码,我确信此代码,因为我在“我的聊天应用程序”中使用了它。

String data=" ";

socket = new Socket("localhost",999);
while(true)
        {
           dos = new DataOutputStream(socket.getOutputStream());
           dis =  new DataInputStream(socket.getInputStream());
           data = dis.readUTF();
           jta.append(data +"\n");
        }

其中 jta 是 JTextArea。

它适用于客户端

,现在适用于服务器端:

try
{

server = new ServerSocket(999);     

Socket  soc = server.accept();  

        while(true)
        {
            String data="";
            try
            {                   
                dis = new DataInputStream(soc.getInputStream());
                dos = new DataOutputStream(soc.getOutputStream());
                data = dis.readUTF();
            }
            catch(Exception e)
            { }
            jta.append(data + "\n");
        }
    }
    catch (IOException e) 
    {
        JOptionPane.showMessageDialog(this, e);
        System.exit(-1);
    }

You can use UTF encoding for getting Full String of Message.

U can try this code and I am Sure About this code because i used it in My Chat Application.

String data=" ";

socket = new Socket("localhost",999);
while(true)
        {
           dos = new DataOutputStream(socket.getOutputStream());
           dis =  new DataInputStream(socket.getInputStream());
           data = dis.readUTF();
           jta.append(data +"\n");
        }

Where jta is JTextArea.

It's for Client Side

Now For Server Side:

try
{

server = new ServerSocket(999);     

Socket  soc = server.accept();  

        while(true)
        {
            String data="";
            try
            {                   
                dis = new DataInputStream(soc.getInputStream());
                dos = new DataOutputStream(soc.getOutputStream());
                data = dis.readUTF();
            }
            catch(Exception e)
            { }
            jta.append(data + "\n");
        }
    }
    catch (IOException e) 
    {
        JOptionPane.showMessageDialog(this, e);
        System.exit(-1);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文