Programming/Java2014. 3. 25. 00:33
TCP는 소켓 자체가 서버용/클라이언트 용으로 나뉘지만
UDP는 컨스트럭터의 인자에 따라서 서버용과 클라이언트용으로 구분된다.

ServerSocket은
accpet() 시에 다른 포트를 return 하게 되는데
이는 서비스 포트를 접속용으로 사용하게 되면 다른 클라이언트들이 접속할 수 없게 되므로 서비스 포트를 비워두기 위함이다.

Server ready...
SRV SOCK localport 3333
ACC SOCK localport 3333, port 2914
Server ready...
SRV SOCK localport 3333
ACC SOCK localport 3333, port 2915 

System.out.println("SRV SOCK localport " + serverSocket.getLocalPort());
System.out.println("ACC SOCK localport " + socket.getLocalPort() + ", port " + socket.getPort()); 




TCP
Server Socket
Socket accept() 
Listens for a connection to be made to this socket and accepts it.
 

[링크 : http://download.java.net/jdk8/docs/api/java/net/ServerSocket.html  

ServerSocket serverS = new ServerSocket(port);
Socket tcpSocket = serverS.accept();
InputStream is = tcpSocket.getInputStream();
OutputStream os = tcpSocket.getOutputStream();
BufferedReader bufferR = new BufferedReader(new InputStreamReader(is));
BufferedWriter bufferW = new BufferedWriter(new OutputStreamWriter(os)); 

bufferR.read();

bufferW.write();
bufferW.flush(); 

Client Socket
Socket tcpSocket = new Socket(ip, port);
InputStream is = tcpSocket.getInputStream();
OutputStream os = tcpSocket.getOutputStream();
BufferedReader bufferR = new BufferedReader(new InputStreamReader(is));
BufferedWriter bufferW = new BufferedWriter(new OutputStreamWriter(os)); 

bufferR.read();

bufferW.write();
bufferW.flush(); 

[링크 : http://download.java.net/jdk8/docs/api/java/net/Socket.html
 


UDP
DatagramPacket(byte[] buf, int length) Constructs for receiving
DatagramPacket(byte[] buf, int length, InetAddress address, int port) Constructs for sending
[링크 : http://download.java.net/jdk8/docs/api/java/net/DatagramPacket.html]

DatagramSocket(int port) Constructs a datagram socket and binds it to the specified port on the local host machine.
DatagramSocket(int port, InetAddress laddr) Creates a datagram socket, bound to the specified local address.

void receive(DatagramPacket p) Receives a datagram packet from this socket.
void send(DatagramPacket p) Sends a datagram packet from this socket.
[링크 : http://download.java.net/jdk8/docs/api/java/net/DatagramSocket.html] 

DatagramSocket ds = new DatagramSocket(port);
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

ds.receive(dp);
ds.send(dp);



'Programming > Java' 카테고리의 다른 글

jdk 1.5 - annotation / @  (0) 2014.05.08
java <-> c 상호호출  (0) 2014.03.25
java object serializable / ObjectInputStream + ObjectOutputStream  (0) 2014.03.24
Java Input/OutputStream 관련  (0) 2014.03.21
java 8을 윈XP에 설치하자?  (2) 2014.03.20
Posted by 구차니