简体   繁体   English

Java套接字与服务器端断开连接

[英]java socket disconnected from server side

I am facing a problem regarding sockets on the server side. 我在服务器端遇到有关套接字的问题。 My code is client side. 我的代码是客户端。 Whenever I am sending a second message (whether it's a heartbeat or any other message) it will fail on the server, and the server side logs an 'error in message format' but the same message will succeed the first time. 每当我发送第二条消息(无论是心跳或其他任何消息)时,它将在服务器上失败,并且服务器端记录“消息格式错误”,但同一条消息将首次成功。 Please help me out with this. 这个你能帮我吗。 my client code : 我的客户代码:

    public class Main {

        String Host = "";
        int port = 1111;
        Socket ss;
        BufferedReader in;
        BufferedWriter out;
        String recv;

        public void connection() {
            try {

                ss = new Socket(Host, port);
                ss.setSoTimeout(30000);

                in = new BufferedReader(new InputStreamReader(ss.getInputStream()));
                out = new BufferedWriter(new OutputStreamWriter(ss.getOutputStream()));

            } catch (UnknownHostException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public void sender(String regTag) {

            if (ss == null || !ss.isConnected()) {
                connection();
            }
            try {

                if (out != null && regTag != null) {
                    out.write(regTag + "\n");
                    System.out.println("message::" + regTag);
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public String Reciver() {

            try {

                recv = in.readLine();
                if (ss != null && recv != null) {
                    return recv;
                } else {
                    disconnect();
                    String Str = "nothing...Sorry";
                    return Str;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "Exception";
            }
        }

        public void disconnect() {
            try {
                System.out.println("socket discoonected.");
                ss.close();
                in.close();
                out.close();
                connection();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static void main(String[] args) {


            Main me = new Main();
            me.connection();
            String hbhb = "`SC`0004HBHBB7BDB7BD";
            String login = "`SC`00581.000000CRBTSRVM    00000001DLGLGN    00000002 TXBEG    LOGIN:USER=cvbs,PSWD=password   DEB2CCA8";
            String cut = "`SC`00631.000000CRBT00PPSPHS00000002DLGCON    00000003 TXBEG    CUT PPS FEE:MDN=9610023,CUTFEE=1000,REASON=1   BDB7DA88";
            me.sender(hbhb.trim());
            String str = me.Reciver();
            System.out.println("Response :::" + str);
            me.sender(login.trim());
            String str1 = me.Reciver();
            System.out.println("Response hb:::" + str1);
}

It receives null ... all the time on every second message 它总是在每隔第二条消息上收到null

logs from serverside 来自服务器端的日志

[121_SERVER] 2012-05-03 14:26:37:213 [ERROR] [ServerAccptor.java:254] ->
errorCode = [UIP-80015] errorDesc = [Uip server has a exception when receiving data from the client,will remove the client,Server [adapter id=121],.]
        at com.ztesoft.zsmart.bss.uip.adapter.socket.server.ServerAccptor.listenMsg(ServerAccptor.java:252)
        at com.ztesoft.zsmart.bss.uip.adapter.socket.server.ServerAccptor.run(ServerAccptor.java:117)
Caused by: errorCode = [UIP-9102] errorDesc = []  Describing= [read client message error,will remove client.]
        at com.ztesoft.zsmart.bss.uip.adapters.socket.server.mml.MMLServerAdapter.readByteField(MMLServerAdapter.java:784)
        at com.ztesoft.zsmart.bss.uip.adapters.socket.server.mml.MMLServerAdapter.reciveWholeMsg(MMLServerAdapter.java:671) 

Your code embodies numerous bad practices and fallacies. 您的代码体现了许多不良做法和谬论。

  1. You are logging exceptions and otherwise ignoring them, and doing strange things like letting the program continue, returning "Exception", etc. This is poor programming. 您正在记录异常,否则将其忽略,并进行一些奇怪的事情,例如让程序继续运行,返回“ Exception”等。这是糟糕的编程。 Exceptions are there to help you, not to have bandaids applied them to hide the blood. 有例外可以帮助您,不要让创可贴将它们掩盖起来。 The code will not self-heal under the bandaid. 该代码在创可贴下不会自愈。 For example you should just declare connection() to throw IOException and let the callers deal with it. 例如,您只需要声明connection()即可引发IOException并让调用者对其进行处理。

  2. As a consequence of (1) you have numerous ss != null tests. 作为(1)的结果,您有许多ss != null测试。 You shouldn't even be in a state where you need to do I/O and ss could be null . 您甚至不应该处于需要执行I / O并且ss可以为null Again correct exception handling and propagation would avoid this. 同样,正确的异常处理和传播将避免这种情况。

  3. As a further result of (1), you have numerous !ss.isConnected() tests, apparently in the mistaken belief that this API will tell you if the connection has been dropped. 作为(1)的进一步结果,您有许多!ss.isConnected()测试,显然是错误地认为此API会告诉您是否断开了连接。 It won't. 不会的 It will only tell you whether you have connected the Socket yet. 它只会告诉您是否已连接Socket In your code, as you are calling ss = new Socket(...) , you have connected it, or else you haven't executed that code yet. 在您的代码中,当您调用ss = new Socket(...) ,您已经连接了它,否则您尚未执行该代码。 Calling isConnected() adds no value. 调用isConnected()不会增加任何值。

  4. You are closing the socket input stream before the output stream. 您要在输出流之前关闭套接字输入流。 This is incorrect. 这是不正确的。 You should close only the output stream, and the socket itself in a finally block. 您应该关闭输出流,并在finally块中关闭套接字本身。 That way the output stream gets flushed. 这样,输出流将被刷新。 Closing the input stream closes the socket and the output stream without flushing it. 关闭输入流会关闭套接字,而不会刷新输出流。 Don't do that. 不要那样做

Actually the correct answer is that there is no \\n in the MML response. 实际上,正确的答案是MML响应中没有\\n So this never works: 因此,这永远行不通:

recv = in.readLine();   

You have to read the message length given in the message header part of the response and read up to that length. 您必须读取响应的消息头部分中给出的消息长度,并读取到该长度。

UPDATE: 更新:

  1. there are syntax errors in your MML commands. 您的MML命令中存在语法错误。 It seems that you are using version 1.00 of the protocol, so this is a sample that works (look for differences): 似乎您正在使用协议的1.00版,因此这是一个有效的示例(查找差异):

     `SC`00741.00CRBT PPS 00000001DLGCON 00000004TXBEG PPS CUT FEE:mdn=93784050910,fee=300,id=20140812165011003 F3E0ADDF 

You must fill the extra spaces with 0 just in numbers, elsewhere you have to fill them with blank spaces. 您必须仅用数字0填充多余的空格,否则必须用空格填充。

暂无
暂无

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

相关问题 Android-通过套接字编程连接的Java。 设备与网络断开连接后,dataoutputstream写操作在Java端不会失败 - Android - java connected via socket programming. dataoutputstream write does not fail on the java side after the device is disconnected from network 将字节流从服务器端java中的套接字转换为字符串 - convert byte stream to string from socket in server side java Java Socket 服务器 - 客户端; 卡在服务器端 - Java Socket Server - Client; Stuck on Server side Java中的客户端套接字编程-从服务器端写入客户端套接字的麻烦 - Client-socket programming in Java - trouble with writing to the client socket from server side 客户端未向服务器 Java Socket 发送消息 - Client side is not sending message to server Java Socket Java套接字:检查客户端套接字是否已断开连接 - Java Socket: Check if Client socket is disconnected 写入套接字比另一端读取速度更快时如何避免Java服务器挂起 - How to avoid java server from hanging when writing faster to a socket than the other side reads 如何从客户端关闭套接字通道,以便服务器引发java.nio.channels.ClosedChannelException - How to close a socket channel from client side so that the server throws java.nio.channels.ClosedChannelException 无法在服务器端接收数据(Java套接字编程) - Unable to receive data on server side (Java Socket Programming) Java TCP套接字无法将文件发送到服务器端 - java tcp socket can't send file to server side
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM