How To: Open Client Socket in Java With Timeout どのように:クライアントのソケットを開いて、 Javaと、タイムアウト
Often we need to create a (client) socket connection in java but we do not want to wait indefinitely for the connection to open.を作成する必要がしばしば私たち(クライアント) Javaのソケット接続をしたいわけではありませんを無期限に待機への接続をオープンします。 We need a way to timeout socket connections.私たちを必要とするソケット接続がタイムアウトする方法です。 Two solutions and recommended code. 2つのソリューションと推奨コードです。
Previously the only way was to create the socket in a Thread.以前は次の唯一の方法は、ソケットのスレッドを作成しています。 And then kill the thread if it is running beyond a threshold time limit.スレッドを台無しにすると入力し、実行中の場合には時間制限しきい値を超えています。 This had two problems.これは2つの問題が発生します。 First Thread.kill or Thread.suspend are deprecated methods and with good reason.最初のthread.killまたはメソッドとthread.suspendは、正当な理由が推奨されていません。 Their availability cannot be ensured in future versions of Java.空室状況を確保することはできませんが、将来のバージョンのJavaです。 Secondly the process was clumsy to say the least.第二のプロセスは、控えめに言っても不器用な。 Now we have a better method since JDK 1.4.今すぐ私たちのJDK 1.4以降は、より良い方法です。
java.net.Socket supports timeout from JDK1.4 onwards. JDK1.4のタイムアウトからjava.net.socket以降をサポートしています。 The following is a sample code to enable socket timeout in Java.は、次のサンプルコードは、ソケットのタイムアウトを有効にしています。 In this sample 500 milliseconds is chosen as timeout value.このサンプルでは500ミリ秒のタイムアウト値に選ばれました。
// Open a socket without any parameters. / /ソケットを開いて任意のパラメータです。 It hasn't been binded or connectedにバインドされていないことや、接続さ
Socket sock = new Socket();ソケットの靴下=新しいソケット( ) ;
// Bind to a local ephemeral port / /バインドして、ローカルephemeralポート
sock.bind(null); sock.bind (ヌル) ;
// Connect to google.com on port 80 with a timeout of 500 milliseconds / / google.comのポートに接続して80とすると、タイムアウトを500ミリ秒
sock.connect(new InetSocketAddress("www.google.com", 80), 500 ); sock.connect (新inetsocketaddress ( " www.google.com "と、 80 ) 、 500 ) ;
// Your code goes here / /あなたのコードがここに
// Close the socket. / /クリックして、 [ソケットを提供します。
sock.close(); sock.close ( ) ;
Filed under提出されて Headline Newsニュースの見出し , 、 How Toどのように , 、 Java Software Javaソフトウェア , 、 Tech Note技術のノート | |
| |
RSS 2.0 RSS 2.0を | |
Trackbackトラックバック this Article |この記事|
Email this Article電子メールこの記事
You may also like to readを読むようにすることも可能 |



































