16行目: 16行目:


==例==
==例==
  Socket s = new Socket("hoge.com", 80);
  Socket skt = new Socket("hoge.com", 80);
  OutputStream os = s.getOutputStream();
  OutputStream os = skt.getOutputStream();
  os.write("GET /index.html HTTP/1.0\r\n".getBytes());
  os.write("GET /index.html HTTP/1.0\r\n".getBytes());
  os.write("\r\n".getBytes());
  os.write("\r\n".getBytes());
  os.flush();
  os.flush();
  InputStream is = s.getInputStream();
  InputStream is = skt.getInputStream();
  InputStreamReader isr = new InputStreamReader(is);
  InputStreamReader isr = new InputStreamReader(is);
  int i = isr.read();
  int i = isr.read();
28行目: 28行目:
     i = isr.read();
     i = isr.read();
  }
  }
  s.close();
  skt.close();

2019年7月3日 (水) 08:43時点における版

java.net.Socket [1]

私はソケットを用意します。ソケットとは、2つのマシン間で通信を行う時に利用する端点のことです。

コンストラクタ

  • public Socket(String host, int port) - 指定されたホスト上の指定ポートに接続
  • public Socket(InetAddress address, int port) - 指定されたIPアドレスの指定ポートに接続

メソッド

  • isConnected - ソケットの接続状態を真偽する
  • getInetAddress - ソケットの接続先のアドレスを知らせる
  • getInputStream - ソケットの入力ストリームを返す
  • getOutputStream - ソケットの出力ストリームを返す
  • getPort - 接続先のリモート・ポート番号を知らせる
  • close - ソケットを閉じる

Socket skt = new Socket("hoge.com", 80);
OutputStream os = skt.getOutputStream();
os.write("GET /index.html HTTP/1.0\r\n".getBytes());
os.write("\r\n".getBytes());
os.flush();
InputStream is = skt.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int i = isr.read();
while (i != -1) {
    System.out.print((char) i); 
    i = isr.read();
}
skt.close();