Java 基于 UDP 协议的 Socket 编程 ——客户端程序

2023-03-09 19:02:45 浏览数 (3)

代码语言:javascript复制
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Main { // 别忘记了抛出异常
	public static void main(String[] args) throws IOException {
		DatagramSocket ds = new DatagramSocket();
		
		//准备发送数据
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 创建读入,就是BufferedReader 的读入,和Scanner 差不多
		String strSend = br.readLine(); // 读入数据
		br.close();
		DatagramPacket dpSend = new DatagramPacket(strSend.getBytes(),strSend.getBytes().length,InetAddress.getLocalHost(),5000); //打包
		ds.send(dpSend);
		
		byte[] buf = new byte[1024];  //接收服务器返回的结果阿女
		DatagramPacket dpReceive = new DatagramPacket(buf,buf.length); 
		ds.receive(dpReceive);// 结果的接受,放到dpReceive
		System.out.println("客户端接受到"   new String(dpReceive.getData(),0,dpReceive.getLength()));
		
		ds.close();
	}
}

0 人点赞