为什么接收端开着,发送端发送数据,接收端确无法- package com.itheima.net;
- import java.net.*;
- public class UDPSend {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- try {
- send();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static void send() throws Exception{
- //建立UDPSocket服务。
- DatagramSocket ds = new DatagramSocket();
- //提供数据,打包。
- byte[] buf = "hello,word".getBytes();
- DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.2"),10000);
- //数据发送。
- ds.send(dp);
- //关闭资源
- ds.close();
- }
- }
- <DIV class=blockcode>
- <BLOCKQUOTE>import java.net.*;
- class UDPReceive {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- try {
- receive();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static void receive() throws Exception{
- DatagramSocket ds = new DatagramSocket(10000);
- while(true){
- byte[] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf,buf.length);
- ds.receive(dp);
- String ip=dp.getAddress().getHostAddress();
- String data = new String(dp.getData(),0,dp.getLength());
- int port = dp.getPort();
- System.out.println("ip:"+ip);
- System.out.println("data:"+data);
- System.out.println("port:"+port);}
- // ds.close();
- }
- }
复制代码
接收数据? |
|