[计网编程]UDP套接字编程

package ClientAndServer;

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

public class UDPClient1 {
	public static void main(String[] args) throws IOException{
		InetAddress address = InetAddress.getByName("localhost");
		int port = 8080;
		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);
		/*Constructs a DatagramPacket for receiving packets of length length. 
The length argument must be less than or equal to buf.length.*/
		socket.receive(packet2);
		
		//读取数据
		String reply = new String(data2,0,packet2.getLength());
		System.out.println("我是客户端,服务器说: "+reply);
		
		socket.close();
	}
}
package ClientAndServer;

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

public class UDPServer1 {
	public static void main(String[] args) throws IOException{
		DatagramSocket socket = new DatagramSocket(8080);
		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);
		
		//向客户端发送响应数据
		//定义客户端的ip地址,端口号,数据
		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();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值