s-day11-UDP多发多收
This commit is contained in:
@@ -0,0 +1,46 @@
|
|||||||
|
package com.inmind.udp02;
|
||||||
|
|
||||||
|
import java.net.DatagramPacket;
|
||||||
|
import java.net.DatagramSocket;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
/*
|
||||||
|
UDP多发多收
|
||||||
|
*/
|
||||||
|
public class UdpClientDemo04 {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
//1.创建客户端对象
|
||||||
|
DatagramSocket ds = new DatagramSocket();
|
||||||
|
//2.创建数据包发送数据
|
||||||
|
Scanner sc = new Scanner(System.in);
|
||||||
|
|
||||||
|
//3.不停地发,用户输入什么就发送什么
|
||||||
|
while (true) {
|
||||||
|
System.out.println("请输入:");
|
||||||
|
String line = sc.nextLine();//阻塞
|
||||||
|
|
||||||
|
if ("exit".equals(line)) {//这样写避免了空指针异常的可能性
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] bytes = line.getBytes();
|
||||||
|
/*
|
||||||
|
public DatagramPacket(byte buf[], int offset, int length,
|
||||||
|
InetAddress address, int port)
|
||||||
|
参数一:封装要发出去的数据
|
||||||
|
参数二:发送出去的数据大小(字节个数)
|
||||||
|
参数三:服务端的IP地址(找到服务器主机)
|
||||||
|
参数四:服务端程序的端口号
|
||||||
|
*/
|
||||||
|
DatagramPacket dp = new DatagramPacket(
|
||||||
|
bytes, bytes.length,
|
||||||
|
InetAddress.getByName("192.168.23.107"), 10023);
|
||||||
|
//4.开始正式发送数据包
|
||||||
|
ds.send(dp);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
System.out.println("程序结束");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.inmind.udp02;
|
||||||
|
|
||||||
|
import java.net.DatagramPacket;
|
||||||
|
import java.net.DatagramSocket;
|
||||||
|
|
||||||
|
//启动服务器,不停地获取客户端的信息
|
||||||
|
public class UdpServerDemo05 {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
System.out.println("服务器启动");
|
||||||
|
//1.创建服务器对象
|
||||||
|
DatagramSocket ds = new DatagramSocket(10023);
|
||||||
|
//2.不停地获取数据包
|
||||||
|
byte[] buffer = new byte[1024 * 64];
|
||||||
|
while (true) {
|
||||||
|
//3.创建出一个数据包,用于接收客户端的数据
|
||||||
|
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
|
||||||
|
//4.服务器正式接收数据包
|
||||||
|
ds.receive(dp);
|
||||||
|
//5.将字节数据转为字符,并显示对应客户端的信息
|
||||||
|
int length = dp.getLength();//获取数据包中字节数据的长度
|
||||||
|
String result = new String(buffer, 0, length);
|
||||||
|
System.out.println(dp.getPort());//获取数据包的端口
|
||||||
|
System.out.println(dp.getAddress().getHostAddress());//获取数据包的IP地址
|
||||||
|
System.out.println(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user