InputStream ๊ณผ OutputStream
๐ InputStream ๊ณผ OutputStream
๋จ์ผ ๋ฐฉํฅ์ผ๋ก ํ๋ฌ๊ฐ๋ ๋ฐ์ดํฐ์ ํ๋ฆ์ ํํํ๋๊ฒ์ผ๋ก
Stream
์ด๋ผ๊ณ ํ๋ค.์ ๋ ฅ ์คํธ๋ฆผ์ ์ถ๋ฐ์ง (ํค๋ณด๋, ํ์ผ) ์์ ์ถ๋ ฅ ์คํธ๋ฆผ์ ๋์ฐฉ์ง (๋ชจ๋ํฐ, ํ์ผ, ํ๋ก๊ทธ๋จ) ์ ๊ด๊ณ๋ฅผ ๋๋ค.
InputStream
Method | descrption |
---|---|
read() | inputstream ์ผ๋ก๋ถํฐ ๋ฐ์ดํฐ์ byte๋ฅผ ์ฝ์ด๋ธ๋ค |
read(byte b[]) | inputstream๊ณผ buffer ๋ฐฐ์ด b ๋ก๋ถํฐ byte๋ก ์ด๋ฃจ์ด์ง ๋ฐ์ดํฐ๋ฅผ ์ฝ์ด๋ธ๋ค |
OutputStream
Method | descrption |
---|---|
flush() | ๋ฒํผ์ ์๋ฅํ๋ ๋ชจ๋ ๋ฐ์ดํธ๋ฅผ ์ถ๋ ฅํ๋ค |
write(byte b[]) | outputstream์ด ๊ฐ๊ณ ์๋ ๋ฐ์ดํธ ๋ฐฐ์ด b๋ฅผ ๋ชจ๋ write ํ๋ค |
์์ผ ํ๋ก๊ทธ๋๋ฐ์์์ I/O Stream
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
while(true) {
//5. ๋ฐ์ดํฐ ์ฝ๊ธฐ
byte buffer[] = new byte[256];
int readByteCount = input.read(buffer);//blocking.
if(readByteCount == -1) {
// ํด๋ผ์ด์ธํธ ์ ์์ข
๋ฃ ํ ๊ฒฝ์ฐ
System.out.println("[server] closed by client.");
break;
}
String data = new String(buffer, 0, readByteCount, "utf-8");
System.out.println("[server] received " + data);
//6. ๋ฐ์ดํฐ ์ฐ๊ธฐ
output.write(data.getBytes("utf-8"));
}
์์ผ ํ๋ก๊ทธ๋๋ฐ์์์
IOStream
์ ์์ฑํ ์์ผ์ผ๋ก๋ถํฐaccept()
์ดํ ์ฐ๊ฒฐ์ด ๋๋ฉด ๊ฐ๊ฐ์stream
๊ฐ์ฒด๋ฅผ ์ป๊ฒ๋๊ณread/write
Method๋ฅผ ์ฌ์ฉํด ๋ฐ์ดํฐ ํต์ ์ด ์ด๋ฃจ์ด์ง๋ค.