码迷,mamicode.com
首页 > 编程语言 > 详细

java之UDP(datagramsocket,datagramPacket)实例

时间:2014-10-28 12:21:31      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:java   网络编程   datagramsocket   datagrampacket   通信   

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.junit.Test;

public class TestUDP {

	@Test
	public void send() throws Exception{
		String str = "Hello";
		DatagramPacket pack = new DatagramPacket(str.getBytes(),str.getBytes().length,InetAddress.getByName("127.0.0.1"),10000);
	    
		DatagramSocket scoket = new DatagramSocket();
		for(int i =0; i< 10;i++){
			scoket.send(pack);
		}
		
		
		scoket.close();
	}
	
	@Test
	public void revice() throws Exception{
		
		byte[] by = new byte[1024];

		DatagramPacket pack = new DatagramPacket(by,by.length);
		
		DatagramSocket scoket = new DatagramSocket(10000);
		while(true){
			scoket.receive(pack);
			
			System.out.println(new String(pack.getData()));
			
		}
		
	}

}

java之UDP(datagramsocket,datagramPacket)实例

标签:java   网络编程   datagramsocket   datagrampacket   通信   

原文地址:http://blog.csdn.net/sd_tz_wzg/article/details/40536711

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!