socket 連線逾時處理 java

來源:互聯網
上載者:User

之前很少做這種純的socket編程,最近公司有項目需要跟pc端通訊,自己定協議發報文,就寫了一個簡單的基於java socket的client。

功能差不多了以後,發現一個問題,向pc端發報文時,pc端ip port 不通的情況下,會一直死等,等到天荒地老。這種情況我剛開始以為是代碼出現了問題。

之前的代碼:

                 Socket socket = null;
                try {
                    socket =new Socket(host,port);//問題出在這裡
                     socket.setSoTimeout(timeout);
                 我以為我設定了逾時:  socket.setSoTimeout(timeout);,其實這個是響應阻塞逾時,是client和服務端建立串連後,等待接收資料的逾時時間,真正的連線逾時我沒有處理。


解決:
                 Socket socket = null;
                try {
                    socket = new Socket();
                    SocketAddress socketAddress = new InetSocketAddress(host, port);
                    socket.connect(socketAddress, 100);//連不上的0.1毫秒斷掉串連
                     socket.setSoTimeout(timeout);//響應阻塞逾時
  這樣就好了   ip連不上的0.1秒就斷開,connectTimeout 異常

參考的這位老哥的 http://blog.csdn.net/tterminator/article/details/52494141  感謝。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.