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

Java UDP 数据报

时间:2015-07-26 00:15:30      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

服务端,创建一个DatagramSocket对象,侦听在某个端口,创建一个DatagramPacket对象接受数据。收到客户端发来的信息后,有原封不动转发到客户端。

public class DatagramServerTest {
	public static void main(String[] args) throws IOException {
		byte[] buf = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buf, 1024);
		DatagramSocket server = new DatagramSocket(9000); //侦听本机9000端口UDP数据包
		
		server.receive(packet);
		
		String str = new String(buf,0,packet.getLength());
		System.out.println("server get msg -> "+packet.getAddress().getHostName()+":"+str);
		
		server.send(new DatagramPacket(buf,packet.getLength(),packet.getAddress(),packet.getPort()));
		
		server.close();
	}
}

 客户端,创建一个DatagramSocket对象和一个DatagramPacket对象(包含目的主机的端口号9000和IP地址),调用send方法,发送数据.然后调用receive接受服务器的回传@

  

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class DatagramClientTest {
	public static void main(String[] args) throws IOException {
		//创建UDP的Socket
        InetAddress serverAddr = InetAddress.getByName("192.168.0.101");	//目的主机IP地址
		DatagramSocket client = new DatagramSocket();//本地端口随机,直接创建DatagramSocket
		
		String str = "hello world, from " + InetAddress.getLocalHost().getHostName();
		DatagramPacket packet = new DatagramPacket(str.getBytes(), str.length(), serverAddr, 9000);	//目的主机端口号9000
		
		client.send(packet);
		byte[] buf = new byte[1024];
		DatagramPacket pkt = new DatagramPacket(buf,1024);
		client.receive(pkt);
		String str1 = new String(buf,0,pkt.getLength());
		System.out.println("client get -> "+packet.getAddress().getHostName()+":"+str1);
		client.close();
	}
}

 

Java UDP 数据报

标签:

原文地址:http://www.cnblogs.com/fangying7/p/4676741.html

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