java UDP

Posted 飞龙dragon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java UDP相关的知识,希望对你有一定的参考价值。

java中UDP的实现氛围两个类:DatagramPacket 和 DatagramSocket

DatagramPacket类将数据填充到UDP包中,这称为数据报,有你来解包接受的数据报.

DatagramSocket可以收发UDP数据报,为收发送数据要将数据放到DatagramPacket中

 

java编程思想UDP client实例

package test;
import java.net.*;
public class Dgram {
    public static DatagramPacket toDatagram(
            String s,InetAddress destIA,int destPort){
        byte[] buf = new byte[s.length() + 1];
        buf = s.getBytes();
        return new DatagramPacket(buf,buf.length,destIA,destPort);
    }
    public static String toString(DatagramPacket p){
        return new String(p.getData(),0,p.getLength());
    }
    
}

//: ChatterClient.java 
// Tests the ChatterServer by starting multiple  
// clients, each of which sends datagrams. 
package test;
import java.lang.Thread; 
import java.net.*; 
import java.io.*; 
 
public class ChatterClient extends Thread { 
  // Can listen & send on the same socket: 
  private DatagramSocket s; 
  private InetAddress hostAddress; 
  private byte[] buf = new byte[1000]; //设置数据包大小,要比发送的数据大
  private DatagramPacket dp =  
    new DatagramPacket(buf, buf.length); //
  private int id; 
 
  public ChatterClient(int identifier) { 
    id = identifier; 
    try { 
      // Auto-assign port number: 
      s = new DatagramSocket(0);//参数不填或是0的话 代表随机选择端口发送
      s.setSoTimeout(10000);//设置超时时间
      hostAddress =  
        InetAddress.getByName("106.13.46.152"); //获得连接端口
    } catch(UnknownHostException e) { 
      System.err.println("Cannot find host"); 
      System.exit(1); 
    } catch(SocketException e) { 
      System.err.println("Can‘t open socket"); 
      e.printStackTrace(); 
      System.exit(1); 
    }  
    System.out.println("ChatterClient starting"); 
  } 
  public void run() { 
    try { 
      for(int i = 0; i < 10; i++) { 
        String outMessage = "Client #" + 
          id + ", message #" + i; 

        // Make and send a datagram: 
        s.send(Dgram.toDatagram(outMessage, 
          hostAddress,  
          ChatterServer.INPORT)); //得到一个DatagramPacket数据包并发送
        // Block until it echoes back: 
        s.receive(dp); //接收数据报
        // Print out the echoed contents: 
        String rcvd = "Client #" + id + 
          ", rcvd from " +  
          dp.getAddress() + ", " +  
          dp.getPort() + ": " + 
          Dgram.toString(dp); 
//        String rcvd = new String(dp.getData(),0,dp.getLength(),"UTF-8");
        System.out.println(dp); 
      } 
    } catch(IOException e) { 
      e.printStackTrace(); 
      System.exit(1); 
    } 
  } 
  public static void main(String[] args) { 
    for(int i = 0; i < 10; i++) 
      new ChatterClient(i).start(); 
  } 
} ///:~

java 网络编程UDP实例

//: ChatterClient.java 
// Tests the ChatterServer by starting multiple  
// clients, each of which sends datagrams. 
package test;
import java.lang.Thread; 
import java.net.*; 
import java.io.*; 
 
public class ChatterClient extends Thread { 
  private final static int PORT = 5000;//要发送的端口
  private static final String HOSTNAME = "106.13.46.152";//要连连接的地址
  
  public static void main(String[] args){
	  try(DatagramSocket socket = new DatagramSocket(0)){//资源自动关闭
		  socket.setSoTimeout(10000);
		  InetAddress host = InetAddress.getByName(HOSTNAME);
		  DatagramPacket request = new DatagramPacket(new byte[1],1,host,PORT);//用于发送的数据报
		  DatagramPacket response = new DatagramPacket(new byte[1024],1024);//用于接收的数据报
		  socket.send(request);//发送
		  socket.receive(response);//接收
		  String result = new String(response.getData(),0,response.getLength(),"UTF-8");
		  System.out.println(result);
	  }catch(IOException e){
		 e.printStackTrace();
	  }
  }
} ///:~

  

以上是关于java UDP的主要内容,如果未能解决你的问题,请参考以下文章

java代码在片段活动中不起作用

java 代码片段【JAVA】

Java之UDP协议 发送与接收简单实现代码

Erlang Udp 服务器丢弃大量数据包

JAVA 网络编程流相关代码(UDP和TCP)

# Java 常用代码片段