ページの作成:「java.net.Socket [https://docs.oracle.com/javase/jp/8/docs/api/java/net/Socket.html] 私はソケットを用意します。ソケット…」
 
17行目: 17行目:
==例==
==例==
  Socket s = new Socket("hoge.com", 80);
  Socket s = new Socket("hoge.com", 80);
InputStream is = s.getInputStream();
  OutputStream os = s.getOutputStream();
  OutputStream os = s.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();
  InputStreamReader isr = new InputStreamReader(is);
  InputStreamReader isr = new InputStreamReader(is);
  int i = isr.read();
  int i = isr.read();

2019年6月27日 (木) 20:08時点における版

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