java2019. 9. 22. 23:07

Simple UDP server & client socket 예제

DatagramSocket 및 DatagramPacket 사용법만 기억

 

ex)



public class DatagramTest {

	
	
	public DatagramTest() {
		super();
		
		new Thread() {
			public void run() {
				startUDPServer();
			}

		}.start();
		
		new Thread() {
			public void run() {
				startUDPClient();
			}

		}.start();
		
	}

	private void startUDPServer() {
		DatagramSocket server = null;
		try {
			
			server = new DatagramSocket(9999);//server 생성
			int bufferLength = 256;
			byte[] buffer = new byte[bufferLength];
			DatagramPacket packet //data 받기 위한 객체를 buffer와 length 크기를 byte 배열로 지정하여 생성
				= new DatagramPacket(buffer, bufferLength);
			while(true) {
				System.out.println("server : waiting for request.");
				server.receive(packet);
				int dataLength = packet.getLength();
				System.out.println("server : received. Data length : "+ dataLength);
				
				//get byte from packet and get it string
				String data = new String(packet.getData(), 0 , dataLength);//
				System.out.println("received data : "+data);
				
				if( data.equals("EXIT")) {
					System.out.println("stop datagram server");
					break;
				}
				
				
			}
			System.out.println("--------------");
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(server != null)
				server.close();				
		}
		
	}
	
	private void startUDPClient() {
		
		for (int loop= 0 ; loop < 3 ; loop++) {
			sendDatagramData("I hate UPD : "+ new Date());
		}
		sendDatagramData("EXIT");
	}

	private void sendDatagramData(String data) {
		try {
			DatagramSocket client = new DatagramSocket();
			/*받을 서버 지정*/
			InetAddress address = InetAddress.getByName("127.0.0.1");
			
			//byte array로 변환
			byte[ ] buffer = data.getBytes();
			
			
			//DatagramPacket 생성 및 포트 지정.
			DatagramPacket packet
			= new DatagramPacket(buffer, 0 , buffer.length, address, 9999);
			
			client.send(packet);
			
			System.out.println("Client: send Data");
			client.close();
			
			Thread.sleep(1000);
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
}

출처 : 자바의 신

'java' 카테고리의 다른 글

코테 유용한 함수 모음 (JAVA)  (0) 2022.01.08
try with resource 구문 예제 (JAVA 7)  (0) 2019.09.24
Simple server & client socket 예제  (0) 2019.09.22
Buffer class의 이해  (0) 2019.09.22
NioSample  (0) 2019.09.22
Posted by easy16