중요한 아이.
UDP 도 통신은 가능함 (주고 받는 것 )
DataGram class 를 이용.
TCP 에서는 Socket class 를 사용함.
client ---------------------
public class Client {
public static void main(String[] args) {
try {
Socket s1 = new Socket("서버주소(ip)", 5430); //클라이언트는 IP address와 포트번호가 필요함.
//복잡하다면 포트는 프로그램이라고 생각하면 됨.(server와 동일한 포트번호)
//
//통신 자체도 읽고 쓰는 것이기때문에 I/O Stream을 사용함.
//보낼때는 당연히 InputStream, 받을 때는 OutputStream
InputStream is = s1.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
System.out.println(ois.readObject());
ois.close();
is.close();
s1.close();
} catch (IOException | ClassNotFoundException e) {
System.err.println("Could not cennect to the server~! =ㅠ=");
}
}
server -------------------------------------------
public class Server {
public static void main(String[] args) {
ServerSocket s = null; // 들어올 수 있는 문을 만들어 주는 Class
try {
s = new ServerSocket(5430); // 만들 때 필요 한 것이 포트번호가 필요하다.
// PC는 포트번호를 통해 각각의 작업을 구별한다.
//0~65536의 포트가 존재함
//보통 0~10000번은 건들지 않는 편, 10001부터 사용하는 게 맘편함
} catch (IOException e) {
e.printStackTrace();
}
while(true){
try {
Socket s1 = s.accept(); // 대기 하면서 client 의 요청을 인식 하는 method
// 요청을 인식하면 새로운 Socket 을 리턴하여 client 에게 응답을 해줌.
// 각각의 요청에 대한 각각의 Socket이 만들어지기 때문에 다중통신이 가능함.
// A client 와 Server 의 Socket 을 B client와 server가 사용할 수 없음.
OutputStream os = s1.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject("Hello net world!");
oos.close();
os.close();
s1.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
'WebStudy > JAVA' 카테고리의 다른 글
BigInteger (0) | 2015.06.05 |
---|---|
StringTokenizer (0) | 2015.06.05 |
Network 네트워크 들어가기 전 토막 상식 - 0 (0) | 2015.06.04 |
특수문자 공백 체크. Pattern, Matcher (0) | 2015.06.03 |
Thread (쓰레드) synchronized 동기화 -05 (0) | 2015.06.03 |