java 基于UDP的Socket网络通信

client代码

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 UDPClient {

	public static void main(String[] args) throws IOException {

		InetAddress address = InetAddress.getByName("localhost");
		
		int port=8801;
		
		byte[] data="用户名:admin;密码:123".getBytes();
		
		DatagramPacket packet=new DatagramPacket(data, data.length, address, port);
		
		DatagramSocket socket=new DatagramSocket();
		
		socket.send(packet);
		
		
		
		byte []data2=new byte[1024];
		
		DatagramPacket packet2=new DatagramPacket(data2, data2.length);
		
		socket.receive(packet2);
		
		String reply=new String(data2, 0, packet.getLength());
		
		System.out.println("接收服务器反馈的信息:"+reply);
		
		socket.close();
	}

}

server代码

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

public class UDPServer {

	public static void main(String[] args) throws IOException {
		
		DatagramSocket socket = new DatagramSocket(8801);

		byte[] data = new byte[1024];

		DatagramPacket packet = new DatagramPacket(data, data.length);

		System.out.println("***服务器已启动,等待客户端发送数据***");

		socket.receive(packet);

		String info = new String(data, 0, packet.getLength());

		System.out.println("服务器接收的数据为" + info);
		
		
		
		InetAddress address=packet.getAddress();
		
		int port=packet.getPort();
		
		byte[] data2="你好啊!".getBytes();
		
		DatagramPacket packet2=new DatagramPacket(data2, data2.length, address, port);
		
		socket.send(packet2);
		
		socket.close();
	}

}


你可能感兴趣的:(java)