2

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) 
4

2 回答 2

4

您的代码体现了许多不良做法和谬误。

  1. 您正在记录异常并以其他方式忽略它们,并做一些奇怪的事情,例如让程序继续,返回“异常”等。这是糟糕的编程。有例外可以帮助您,而不是用创可贴来隐藏血液。代码在创可贴下不会自我修复。例如,您应该只声​​明connection()throwIOException并让调用者处理它。

  2. 作为(1)的结果,你有很多ss != null测试。您甚至不应该处于需要进行 I/O 的状态并且ss可能是null. 再次正确的异常处理和传播将避免这种情况。

  3. 作为 (1) 的进一步结果,您进行了大量!ss.isConnected()测试,显然错误地认为该 API 会告诉您连接是否已断开。它不会。它只会告诉您是否已连接Socket。在您的代码中,当您调用ss = new Socket(...)时,您已经连接了它,否则您还没有执行该代码。调用isConnected()不会增加任何价值。

  4. 您在输出流之前关闭套接字输入流。这是不正确的。您应该在 finally 块中关闭输出流和套接字本身。这样输出流就会被刷新。关闭输入流会关闭套接字和输出流而不刷新它。不要那样做。

于 2012-05-07T10:08:48.400 回答
0

实际上正确的答案是响应中\n没有MML。所以这永远不会奏效:

recv = in.readLine();   

您必须阅读响应的消息头部分中给出的消息长度并读取到该长度。

更新:

  1. MML您的命令中有语法错误。您似乎使用的是协议的 1.00 版本,因此这是一个有效的示例(查找差异):

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

您必须用数字填充多余的空格,0在其他地方您必须用空格填充它们。

于 2014-08-17T07:50:46.067 回答