欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

UDP网络编程

时间:2023-06-09

package UDP;import org.junit.Test;import java.io.IOException;import java.net.*;public class UDPTest { @Test public void send() throws IOException {// 1. DatagramSocket socket = new DatagramSocket();// 将信息都放在DatagramPacket中 String str = "我是UDP发送的信息"; byte[] data = str.getBytes(); InetAddress ip = InetAddress.getLocalHost(); DatagramPacket packet = new DatagramPacket(data, 0, data.length, ip, 8090);// 2. socket.send(packet); socket.close(); } @Test public void receiver() throws IOException {// 1.接收端指定端口号 DatagramSocket socket = new DatagramSocket(8090); byte[] buffer = new byte[100]; DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);// 将接受的信息保存到buffer[]中 socket.receive(packet); System.out.println(new String(packet.getData(),0,packet.getLength())); socket.close(); }}

 

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。