1. 程式人生 > >java_udp傳送端和接收端建立

java_udp傳送端和接收端建立

傳送端:

package cn.itcast.udp.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/*
 * 傳送端:
 * 1、建立udp的Socket;
 * 2、把資料放到包裡邊;
 * 3、把包傳送裡的資料傳送出去
 * 4、關閉資源
 * */
public class UdpDemoSend2 {

	public static void main(String[] args) throws IOException {
		
		System.out.println("傳送端啟動");
		
		//1、建立udp的Socket
		DatagramSocket ds=new DatagramSocket(8888);
		
		//2、把資料放到包裡
		BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
		String len=null;
		
		while((len=buf.readLine())!=null) {
			
			byte[]buff=len.getBytes();
			DatagramPacket dp=
				new DatagramPacket(buff, buff.length, InetAddress.getByName("192.168.1.216"), 11111);
			
		//3、使用udp將資料包傳送出去,使用Send方法
		ds.send(dp);
		if("over".equals(len))
				break;
		}

		//4、關閉流
		ds.close();
		
	}

}

接受端:

package cn.itcast.udp.demo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;


/**
 * 
 * 接受端:
 * 1、建立udp的socket服務
 * 2、建立資料包,用於儲存接受到的資料
 * 3、使用socket中的receive方法吧資料儲存在資料包中
 * 4、使用資料包中的方法解析資料包中的資料
 * 5、關閉資源
 * 
 * */
public class UdpDemoRecever2 {

	public static void main(String[] args) throws IOException {
		
		System.out.println("接收端啟動");
		
//		1、建立udp的socket服務
		DatagramSocket ds=new DatagramSocket(11111);
		
//		2、建立資料包用於儲存接收到的資料
		byte[]buff=new byte[1024];
		DatagramPacket dp=new DatagramPacket(buff, buff.length);
		
		while(true) {
//		3、將資料儲存到資料包中
		ds.receive(dp);
		
//		4、通過資料包中的方法,解析其中的資料,如ip地址,埠號,內容
		String ip=dp.getAddress().getHostAddress();
		int port=dp.getPort();
		String date=new String(dp.getData(), 0, dp.getLength());
		
		System.out.println(ip+":::"+port+":::"+date);
		
		}
//		5、關閉流
//		ds.close();
		
	}

}