码迷,mamicode.com
首页 > 其他好文 > 详细

UDP

时间:2016-08-15 14:25:19      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

我们通过以下代码来连了解以下UPD

首先我们先创建Server类

package cn.a.qwe;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Server {
	public static void main(String[] args) throws Exception {
		DatagramSocket sockets=new DatagramSocket(50000);
		
		byte[] bytes = new byte[1024];
		
		DatagramPacket packet = new DatagramPacket(bytes, 0,bytes.length);
		
		sockets.receive(packet);
		
		byte[] data = packet.getData();
		
		String temp = new String(data,0,data.length);
		System.out.println(temp);
	}
}

紧接着我们来创建一个Client类

package cn.a.qwe;

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

public class Client {
	public static void main(String[] args) throws Exception {
		String word="开启成功";
		byte[] bytes=word.getBytes();
		DatagramSocket client = new DatagramSocket();
		DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, InetAddress.getByName("localhost"), 50000);
		client.send(packet);
	}
}

启动之后我们可以看到当Client运行时,我们可以看到Server类会有"开启成功"的字段输出

 

UDP

标签:

原文地址:http://www.cnblogs.com/baixingqiang/p/5772735.html

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