欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java编程实现基于UDP协议传输数据的方法

程序员文章站 2024-03-06 18:09:44
本文实例讲述了java编程实现基于udp协议传输数据的方法。分享给大家供大家参考,具体如下: udp协议(user datagram protocol,用户数据报协议)不...

本文实例讲述了java编程实现基于udp协议传输数据的方法。分享给大家供大家参考,具体如下:

udp协议(user datagram protocol,用户数据报协议)不同于tcp协议,它是不可能靠的,但是它比tcp协议具有更快的传输速度,udp发送的数据单元称为数据报,当网络传输udp传输udp数据报是无法保证数据能够到达目的地,也无法保证按发送的顺序到达目的地,也就是说先发送了“hello”,再发送了“world”,但接收方可能会先收到“world”,再收到“hello”,也有可能收不到数据,为什么呢?因为它是不可能靠的,在传输途中可能丢失了。但udp比tcp跟适合与传输实时音频。下面是一个简单的upd传输数据报的例子

服务器端:

import java.io.ioexception; 
import java.net.datagrampacket; 
import java.net.datagramsocket; 
import java.net.socketexception; 
public class echoserver { 
 private datagramsocket datagramsocket; 
 private final int port = 8088; 
 public static void main(string[] args) throws socketexception { 
  new echoserver().service(); 
 } 
 public echoserver() throws socketexception{ 
  datagramsocket = new datagramsocket(port); 
  system.out.println("服务器启动"); 
 } 
 public string echo(string msg){ 
  return "echo:"+msg; 
 } 
 public void service(){ 
  while (true) { 
   try { 
    datagrampacket packet = new datagrampacket(new byte[512], 512); 
    datagramsocket.receive(packet); 
    string msg = new string(packet.getdata(), 0, packet.getlength()); 
    system.out.println(packet.getaddress()+"/"+packet.getport()+" msg:"+msg); 
    packet.setdata(echo(msg).getbytes()); 
    datagramsocket.send(packet); 
   } catch (ioexception e) { 
    e.printstacktrace(); 
   } 
  } 
 } 
}

客户端:

import java.io.bufferedreader; 
import java.io.ioexception; 
import java.io.inputstreamreader; 
import java.net.datagrampacket; 
import java.net.datagramsocket; 
import java.net.inetaddress; 
import java.net.socketexception; 
public class echoclient { 
 private string remotehost="localhost"; 
 private int remoteport=8088; 
 private datagramsocket datagramsocket; 
 public echoclient() throws socketexception{ 
  datagramsocket = new datagramsocket(); 
 } 
 public static void main(string[] args) throws socketexception { 
  new echoclient().talk(); 
 } 
 public void talk(){ 
  try { 
   bufferedreader reader = new bufferedreader(new inputstreamreader(system.in)); 
   string msg = null; 
   inetaddress address = inetaddress.getbyname(remotehost); 
   while ((msg=reader.readline())!=null) { 
    //发送数据报 
    byte [] buffer = msg.getbytes(); 
    datagrampacket packet = new datagrampacket(buffer,buffer.length, address, remoteport); 
    datagramsocket.send(packet); 
    //接收数据报 
    datagrampacket inputpacket = new datagrampacket(new byte[512], 512); 
    datagramsocket.receive(inputpacket); 
    system.out.println(new string(inputpacket.getdata(), 0 , inputpacket.getlength())); 
    if("bye".equals(msg)){ 
     break; 
    } 
   } 
  } catch (ioexception e) { 
   e.printstacktrace(); 
  }finally{ 
   datagramsocket.close(); 
  } 
}

希望本文所述对大家java程序设计有所帮助。