2012年5月19日土曜日

HelloWorld(Socket編)

Socketを使ったHelloWorldです。
クライアントがサーバにアクセスするとhelloという文字列が返却されます。

ServerTest.java
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
 public static void main(String[] args) {
  int port = 5000;
  try {
   ServerSocket serverSocket = new ServerSocket(port);
   while (true) {
    Socket socket = serverSocket.accept();
    OutputStream os = socket.getOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    dos.writeBytes("hello");
    socket.close();
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}
ClientTest.java
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ClientTest {
  public static void main(String[] args) {
  String host = "localhost";
  int port = 5000;
  Socket socket = new Socket();
  try {
   socket.connect(new InetSocketAddress(host, port));
   InputStream is = socket.getInputStream();
   DataInputStream dis = new DataInputStream(is);
   byte[] buffer = new byte[1024];
   StringBuffer sb = new StringBuffer();
   int length = 0;
   while ((length = dis.read(buffer)) != -1) {
    sb.append(new String(buffer, 0, length));
    System.out.println(sb.toString());
   }
   socket.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

0 件のコメント: