UDP를 이용한 두 호스트 통신

1. 수락자를 만든다.
package com.tiger.udp;

import java.io.*;
import java.net.*;
import java.util.Scanner;
/**
 * UDP    
 * 1、  :     :127.0.0.1,     : 5555
 * 2、     UDP       (packet),       : 
 * 		(1)  
 * 		(2)     
 * 		(3)    Address
 * 		(4)    Port
 * @author tiger
 * @Date 2017 8 2 
 */
public class Sender {
	public static void main(String[] args) {
		DatagramSocket socket = null;
		DatagramPacket p = null;
		Scanner sc = new Scanner(System.in);
		System.out.println("          :");
		try {
			socket = new DatagramSocket();
			InetAddress ia = InetAddress.getByName("127.0.0.1");
			//            
			String content = sc.nextLine();
			System.out.println(content);
			p = new DatagramPacket(content.getBytes(), content.getBytes().length, ia, 5556);
			socket.send(p);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}package com.tiger.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
 * UDP    
 *   :1、        
 * 
 * @author tiger
 * @Date 2017 8 2 
 */
public class Receiver {
	final static int PORT = 5556;

	public static void main(String[] args) {

		DatagramSocket socket = null;
		DatagramPacket p = null;
		try {
			System.out.println("    。。。。");
			socket = new DatagramSocket(PORT);

			byte[] buff = new byte[1024];
			p = new DatagramPacket(buff, 50);

			//        ,       ,            。
			socket.receive(p);

			byte[] temp = p.getData();
			int size = p.getLength();
			if (size > 0) {
				String content = new String(temp,0,size,"UTF-8");
				System.out.println("     :"+content);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

2. 발송자를 창설한다.

좋은 웹페이지 즐겨찾기