<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> 1 import java.net.*;
2
3 public class UdpRecv
4 {
5 public static void main(String args[]) throws Exception
6 {
7 DatagramSocket ds = new DatagramSocket(3000);
8 byte [] buf = new byte[1024];
9 DatagramPacket dp = new DatagramPacket(buf,1024);
10 ds.receive(dp);
11 String strRecv = new String (dp.getData(),0,dp.getLength(),"gb2312")+" from "+dp.getAddress().getHostAddress() + ":"+dp.getPort();
12 System.out.println(strRecv);
13 ds.close();
14 }
15
16 }
2
3 public class UdpRecv
4 {
5 public static void main(String args[]) throws Exception
6 {
7 DatagramSocket ds = new DatagramSocket(3000);
8 byte [] buf = new byte[1024];
9 DatagramPacket dp = new DatagramPacket(buf,1024);
10 ds.receive(dp);
11 String strRecv = new String (dp.getData(),0,dp.getLength(),"gb2312")+" from "+dp.getAddress().getHostAddress() + ":"+dp.getPort();
12 System.out.println(strRecv);
13 ds.close();
14 }
15
16 }
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> 1 import java.net.*;
2
3 public class UdpSend
4 {
5 public static void main(String args[])throws Exception
6 {
7 DatagramSocket ds = new DatagramSocket();
8 String str = "hello ,this is a test
";
9 DatagramPacket dp = new DatagramPacket (str.getBytes(),str.length(),InetAddress.getByName("127.0.0.1"),3000);
10 ds.send(dp);
11 ds.close();
12 }
13
14 }
2
3 public class UdpSend
4 {
5 public static void main(String args[])throws Exception
6 {
7 DatagramSocket ds = new DatagramSocket();
8 String str = "hello ,this is a test
";9 DatagramPacket dp = new DatagramPacket (str.getBytes(),str.length(),InetAddress.getByName("127.0.0.1"),3000);
10 ds.send(dp);
11 ds.close();
12 }
13
14 }
本文提供了一个简单的Java UDP通信示例,包括发送端和接收端的实现。发送端向本地主机的3000端口发送了一条测试消息,接收端监听该端口并打印接收到的消息及其来源。
857

被折叠的 条评论
为什么被折叠?



