UDP
1.비 연결 지향 프로그래밍
2.TCP와 달리 연결되지 않은 상태로 데이터 통신을 하기 때문에 패킷이 유실될 가능성이 있다
3.속도 면에서는 큰 장점이 있다. ( 처음 반응속도가 빠르다 )
TCP 서버 포트 6000 / UDP 서버 포트 6000 일 때 충돌이 날까?
나지않는다. 다른 프로토콜이라서 그렇다.
UDP Echo Server
UDPEchoServer.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| public class UDPEchoServer { private static final int PORT = 6000; private static final int BUFFER_SIZE = 1000;
public static void main(String[] args) {
DatagramSocket socket = null;
try { socket = new DatagramSocket(PORT);
DatagramPacket receivePacket = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);
while( true ) { socket.receive( receivePacket );
String message = new String( receivePacket.getData(), 0, receivePacket.getLength(), "UTF-8");
System.out.println( message );
byte[] sendData = message.getBytes( "UTF-8" ); DatagramPacket sendPacket = new DatagramPacket( sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort() );
socket.send( sendPacket ); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if( socket != null && socket.isClosed() == false) { socket.close(); }
} }
}
|
UDP Echo Client
UDPEchoClient.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| public class UDPEchoClient { private static final String SERVER_IP = "192.168.111.1"; private static final int SERVER_PORT = 6000; private static final int BUFFER_SIZE = 1024;
public static void main(String[] args) { DatagramSocket socket = null; Scanner scanner = null;
try { scanner = new Scanner(System.in);
socket = new DatagramSocket();
while (true) {
System.out.print(">>"); String message = scanner.nextLine();
if( "".equals(message)) { continue; }
if( "quit".equals( message )) { break; }
byte[] sendData = message.getBytes("utf-8");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, new InetSocketAddress(SERVER_IP, SERVER_PORT));
socket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket( new byte[ BUFFER_SIZE], BUFFER_SIZE); socket.receive(receivePacket);
message = new String( receivePacket.getData(), 0, receivePacket.getLength(), "UTF-8") ; System.out.println("<<"+message);
} } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (socket != null && socket.isClosed() == false) { socket.close(); } scanner.close(); } } }
|