通信の為のソケットを作成する
import java.net.*;
import java.io.*;
class ExsamSocket {
public static void main(String[] args) {
try {
Socket soc = new Socket("www.applitips.com",80);
System.out.println(soc.getInetAddress());
soc.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
<実行結果>
コンソールに www.applitips.com/208.55.214.127
と表示されます。
Socketクラスのコンストラクタは(hostname,
port番号)で、80はHTTPサーバーのportです。
portとはアプリケーションごとに設定された通信の為の出入り口であり、出入り口につけられた表札と考えれば、イメージし易いかと思います。
ソケットはIPAdressとport番号からなり、これにより、Internet上で特定のマシンの特定のアプリケーションを通信相手として限定できます。
上の例はクライアント側(最初に要求を出す側)の例で、サーバー側のJAVA-programを書く場合は、実行状態で待ち受けするクラスを使います。