900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > [Java网络编程基础]UDP发送和接收数据

[Java网络编程基础]UDP发送和接收数据

时间:2020-03-19 10:27:17

相关推荐

[Java网络编程基础]UDP发送和接收数据

代码如下:

package InetAddressPack;import java.io.IOException;import .*;import java.nio.charset.StandardCharsets;public class SendDemo {public static void main(String[] args) throws IOException {DatagramSocket ds = new DatagramSocket();byte[] bys = "hellp,udp,我来了".getBytes();int len = bys.length;InetAddress address = InetAddress.getByName("192.168.1.123");int port = 10086;DatagramPacket dp = new DatagramPacket(bys,len,address,port);ds.send(dp);ds.close();}}

package InetAddressPack;import java.io.IOException;import .*;import java.nio.charset.StandardCharsets;public class SendDemo {public static void main(String[] args) throws IOException {DatagramSocket ds = new DatagramSocket();byte[] bys = "hellp,udp,我来了".getBytes();// int len = bys.length;// InetAddress address = InetAddress.getByName("192.168.1.123");// int port = 10086;DatagramPacket dp = new DatagramPacket(bys, bys.length,InetAddress.getByName("192.168.1.123"),10086);ds.send(dp);ds.close();}}

代码如下:

package InetAddressPack;import java.io.IOException;import .DatagramPacket;import .DatagramSocket;import .SocketException;public class ReceiveDemo {public static void main(String[] args) throws IOException {DatagramSocket ds = new DatagramSocket(10086);byte[] bys = new byte[1024];DatagramPacket dp = new DatagramPacket(bys,bys.length);ds.receive(dp);byte[] datas = dp.getData();int len = dp.getLength();String dataString = new String(datas,0,len);System.out.println("数据是"+dataString);ds.close();}}

package InetAddressPack;import java.io.IOException;import .DatagramPacket;import .DatagramSocket;import .SocketException;public class ReceiveDemo {public static void main(String[] args) throws IOException {DatagramSocket ds = new DatagramSocket(10086);byte[] bys = new byte[1024];DatagramPacket dp = new DatagramPacket(bys,bys.length);ds.receive(dp);byte[] datas = dp.getData();int len = dp.getLength();// String dataString = new String(datas,0,len);// System.out.println("数据是"+dataString);System.out.println("数据是: "+new String(dp.getData(),0,dp.getLength()));ds.close();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。