본문 바로가기
웹프로그램

Java로 구현하는 간단한 Client & Server 프로그램

by 세이박스 2009. 6. 9.
반응형
자바에서 제공하는 소켓 클래스를 이용하면 다음과 같이 간단하게 Client/Server를 구현 할 수 있다.

// Client
Socket socket = new Socket("www.foo.com", 9000);
OutputStream out = socket.getOutputStream();
out.write("Hello world".getBytes());
out.flush();
out.close(); // only if you want one request-response
byte[] buffer = new byte[2048]; // just a sample size
in = socket.getInputStream();
int bytesRead = in.read(buffer);
in.close(); // only if you want one request-response
System.out.println(new String(buffer, 0, bytesRead));

// Server (www.foo.com)
ServerSocket server = new ServerSocket(9000);
Socket socket = server.accept(); // Normally, the accept() is in a threading loop to keep processing
InputStream in = socket.getInputStream();
byte[] buffer = new byte[2048]; // just a a sample size
int bytesRead = in.read(buffer);
in.close(); // only if you want one request-response
OutputStream out = socket.getOutputStream();
out.write("I received the following from you: ".getBytes());
out.write(value, 0, bytesRead);
out.flush();
out.close(); // only if you want one request-response
반응형