[java]代码库
客户端发送到数据会在控制台显示
1.udp服务器类
package s0220UDP协议发送数据;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import javax.swing.JOptionPane;
public class Server {
public static void main(String [] args) throws IOException{
//1.创建服务端
DatagramSocket server=new DatagramSocket(8888);
//2.准备接受容器
byte[] constainer=new byte[1024];
//3.封装成DatagramPacket
DatagramPacket packet=new DatagramPacket(constainer,constainer.length);
//4.接受数据
JOptionPane.showMessageDialog(null, "服务器已启动");
server.receive(packet);
//5.分析数据
byte[] data=packet.getData();
int len=packet.getLength();
System.out.println(new String(data,0,len));
//6.释放资源
server.close();
}
}
2.客户端类
package s0220UDP协议发送数据;
//服务器和客户端用的是相同的类
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class Client {
public static void main(String [] args) throws IOException{
//1.创建客户端
DatagramSocket client=new DatagramSocket(9998);
//2.准备数据
String msg="udp编程";
byte[] data=msg.getBytes();
//3.打包成DatagramPacket(发送的地点,端口)
DatagramPacket packet=new DatagramPacket(data,data.length,new InetSocketAddress("localhost",8888));
//4.发送
client.send(packet);
//5.释放资源
client.close();
}
}