JAVA网络编程之UDP

JAVA网络编程之UDP

服务器端:

package com.jsd.jsd1408.udp;

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

/**
 * 
 * @Description: udp通讯服务器端
 * @author king-pan   [email protected]
 * @date 2014年10月11日
 * @version V1.0
 */
public class Server {
	public static void main(String[] args) {
		try {
			/*
			 * 创建用于通讯的DatagramSocket
			 */
			DatagramSocket socket=new 	DatagramSocket(3333);
			/*
			 * 接收包数据的byte数组
			 */
			byte[] buf=new byte[1024];//1k
			DatagramPacket packet=new DatagramPacket(buf,buf.length);
			/*
			 * 通过Socket获取客户端发送过来的数据
			 * 经过这个操作后,该包有了变化:
			 * 1:包中的字节数组就存放了客户端发送过来的数据了
			 * 2:包中也记录了数据从哪里来了。
			 * 3:虽然我们定义的是可以装100字节,但接收后
			 *   包也知道了实际收到的字节量了。
			 */
			socket.receive(packet);
			/*
			 * byte[] getDate()
			 * 该方法用于获取包中的字节数组,该字节数组
			 * 就是我们创建包的时候传入的字节数组buf
			 */
			buf = packet.getData();
			/*
			 * int getLength()
			 * 该方法可以得知包中这次接收的实际字节量
			 */
			String message 
				= new String(
					 buf,
					 0,
					 packet.getLength(),
					 "utf-8"
			);
			System.out.println("客户端说:"+message);
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

客户端:

package com.jsd.jsd1408.udp;

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

/**
 * 
 * @Description: udp通讯客户端
 * @author king-pan   [email protected]
 * @date 2014年10月11日
 * @version V1.0
 */
public class Client {
	public static void main(String[] args) {
		try {
			/*
			 * 创建DatagramSocket用于发送数据
			 * 该类封装了UDP协议,用于传输数据
			 */
			DatagramSocket socket
				= new DatagramSocket();
			/*
			 * 准备数据,并进行打包,设置目的地信息
			 */
			String message 
				= "试问挖掘机技术哪家强?";
			byte[] buf
				= message.getBytes("utf-8");
			//创建目的地地址
			InetAddress address
				= InetAddress.getByName("127.0.0.1");
			//设置目的地使用的端口
			int port = 3333;
			//打包
			DatagramPacket sendPacket
				= new DatagramPacket(
					buf,//要发送的数据(字节数据)
					buf.length,//表示将字节数组所有字节发送
					address,//目的地地址
					port//目的地端口号
				);
			
			//将包发送至目的地
			socket.send(sendPacket);
			
			
			
			
			buf = new byte[100];
			DatagramPacket recvPacket
				= new DatagramPacket(
					buf,//接收的数据要存入的字节数组
					buf.length//将接收多少字节存入该数组
				);
			socket.receive(recvPacket);
			buf = recvPacket.getData();
			message 
				= new String(
					 buf,
					 0,
					 recvPacket.getLength(),
					 "utf-8"
			);
			System.out.println("服务端说:"+message);
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


你可能感兴趣的:(java基础,TCP/IP,UDP)