简体   繁体   中英

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

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. 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.

  2. As a consequence of (1) you have numerous ss != null tests. You shouldn't even be in a state where you need to do I/O and ss could be 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. It won't. It will only tell you whether you have connected the Socket yet. In your code, as you are calling ss = new Socket(...) , you have connected it, or else you haven't executed that code yet. Calling isConnected() adds no value.

  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. 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. 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. It seems that you are using version 1.00 of the protocol, so this is a sample that works (look for differences):

     `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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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