Java实现简单的UDP编程

Java实现简单的UDP编程

客户端

package com.udp.service;

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

public class UdpClient {
	public static void main(String[] args) throws Exception {
		//1.创建DatagramSocket数据报包套接字对象
		
		DatagramSocket socket = new DatagramSocket(9000);
		
		String message = "Hello UdpServer";
		byte[] bytes = message.getBytes();
		//2.创建数据包对象
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
		InetAddress inetAddress = null;
		inetAddress = InetAddress.getByName("10.0.41.60");
		packet.setAddress(inetAddress);
		packet.setPort(1010);
		//3.发送数据包
		socket.send(packet);
		
		//创建一个数据包用于接收服务端返回的信息
		byte[] byte2 = new byte[1024];
		DatagramPacket datagramPacket = new DatagramPacket(byte2, byte2.length);
		socket.receive(datagramPacket);
		//解析消息并打印数据
		String string = new String(datagramPacket.getData());
		System.out.println(string);
		System.out.println(datagramPacket.getAddress());
		System.out.println(datagramPacket.getPort());
		//Closes this datagram socket
		socket.close();
	}
}

服务端

package com.udp.service;

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

public class UdpServer {
	public static void main(String[] args) throws IOException {
		byte[] byte1 = new byte[1024];
		//1.创建数据包接受来自客户端的信息
		DatagramPacket datagramPacket = new DatagramPacket(byte1, byte1.length);
		//2.创建数据报包套接字对象
		DatagramSocket socket = new DatagramSocket(1010);
		//3.接受数据包
		socket.receive(datagramPacket);
		InetAddress address = datagramPacket.getAddress();
		int port = datagramPacket.getPort();
		String mess = new String (datagramPacket.getData());
		System.out.println(mess);
		System.out.println(address);
		System.err.println(port);
		
		String message = "来啦,老弟!";
		byte[] bytes2 = message.getBytes();
		//创建数据包 用户发送数据
		DatagramPacket datagramPacket2 = new DatagramPacket(bytes2,bytes2.length,address,port);
		//发送包
		socket.send(datagramPacket2);
		//Closes this datagram socket
		socket.close();
	}
}

你可能感兴趣的:(Java,网络编程)