码迷,mamicode.com
首页 > 编程语言 > 详细

java UDP

时间:2019-03-10 17:49:35      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:style   tip   hat   rom   not   []   发送   网络编程   back   

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

标签:style   tip   hat   rom   not   []   发送   网络编程   back   

原文地址:https://www.cnblogs.com/jiangfeilong/p/10506019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!