如何连接到tcpclient?

时间:2018-12-13 17:06:44

标签: java serversocket dataoutputstream

我正在尝试连接到TCP客户端,并且不断收到ioexception连接被拒绝的错误。我不知道我在做什么错。我正在尝试启用tcp通知。我正在连接到rfid阅读器,并试图将数据返回到我的程序中以插入数据库中。

这是我的代码:

Socket tagServerSocket;
     while (true){
         try{
             String data;
               tagServerSocket = new Socket("localhost", this.notifyPort);
             DataOutputStream outToServer = new 
     DataOutputStream(tagServerSocket.getOutputStream());

             while (true) {

                    try {

                        Thread.sleep(20);
                    } catch (Exception e) {
                        System.err.println(e.getMessage());
                    }   

                    int cnt_rd=0;
                    while((cnt_rd < 10) && (TagBuffer.size() > 0))
                    {

                        synchronized (TagBuffer) {                      
                            if (TagBuffer.size() != 0) {
                                data = "";
                                TagInfo tag = TagBuffer.peek();
                                data += "ReaderIP:" + tag.ipaddr;
                                data += "|ID:" + tag.epc;
                                data += "|Antenna:" + tag.antennaPort;
                                data += "|Timestamp:" + tag.timestamp;
                                data += "|PC:" + tag.pc;
                                data += "|RSSI:" + tag.rssi + "\n";



                                TagBuffer.remove();
                                outToServer.writeBytes(data);


                                cnt_rd++;
                            }

                        }

                    }


             }
                    tagServerSocket.close();
                     tagServerSocket = null;
                     Thread.sleep(10);
                     startup=true;
            } catch (UnknownHostException e) {
                tagServerSocket = null;
                startup=false;
                System.out.println("Unable to connect to port " + 
   this.notifyPort);
        } catch (IOException e) {
                // tagServerSocket = null;
                startup=false;
                String data1 = String.format("00");
                System.out.println("Unable to send tag data to server" + 
data1);
                System.out.println("ioexception tcpclient: 
 "+e.getMessage());
        } catch (InterruptedException e) {
            startup=false;
            e.printStackTrace();
        }


     }

0 个答案:

没有答案