소켓(Socket)
-소켓 통신 기초
-TCP 서버의 기본 구조
ServerSocket servSock = null;
try {
// 서버 소켓을 초기화한다.
servSock = new ServerSocket(9000);
while (true) {
// 클라이언트의 접속을 기다린다.
Socket sock = servSock.accept();
InputStream inStream = sock.getInputStream();
OutputStream outStream = sock.getOutputStream();
// 클라이언트와 데이터를 주고 받는다.
while (true) {
// 데이터 수신
inStream.read(...);
// 데이터 송신
outStream.write(...);
}
sock.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
servSock.close();
}
-소켓을 이용한 서버 작성 절차
-TCP 클라이언트의 기본 구조
Socket sock = null;
try {
// 서버에 접속한다.
sock = new Socket("127.0.0.1", 9000);
InputStream inStream = sock.getInputStream();
OutputStream outStream = sock.getOutputStream();
// 서버와 데이터를 주고 받는다.
while (true) {
// 데이터 송신
outStream.write(...);
// 데이터 수신
inStream.read(...);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
sock.close();
}
-소켓을 이용한 클라이언트 작성 절차