UDP协议全称是用户数据报协议,在网络中它与TCP协议一样用于处理数据包,是一种无连接的协议。在OSI模型中,在第四层——传输层,处于IP协议的上一层。UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的。
正文
今天学习了Java的网络编程,感觉UDP数据传输对于我这种初学者还是有点玩头的,自己就花了点时间写了一个简单的聊天程序和同学玩了玩,此程序使用了多线程,不过暂时存在线程安全问题,后面有时间再优化一下,有兴趣的朋友可以拿去玩玩。
玩法:两台电脑(或者打开两个窗口,电脑需要进行网络连接),然后一边发送,另一边就可以接收,当然双方都是可以进行接收与发送的。其中会将对方的聊天话语存储到文本当中。
import java.io.*; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.text.SimpleDateFormat; import java.util.Date; public class UdpDemo1 { public static void main(String[] args) { UdpSend us = new UdpSend(); UdpAccept ua = new UdpAccept(); Thread th1 = new Thread(us); Thread th2 = new Thread(ua); th1.start(); th2.start(); } } //发送端 class UdpSend implements Runnable{ @Override public void run() { DatagramSocket ds = null; while(true){ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { String str = br.readLine(); byte[] b = str.getBytes("GBK"); DatagramPacket dp = new DatagramPacket(b,b.length, InetAddress.getByName("192.168.202.1"),5555); ds = new DatagramSocket(); ds.send(dp); } catch (IOException e) { e.printStackTrace(); } } } } //接收端 class UdpAccept implements Runnable{ public String path = "F:"+File.separator+"test"+File.separator+"jilu.txt"; @Override public void run() { DatagramSocket ds = null; try { ds = new DatagramSocket(5555); } catch (SocketException e) { e.printStackTrace(); } while(true){ try { byte[] b = new byte[1024]; DatagramPacket dp = new DatagramPacket(b,b.length); ds.receive(dp); String str = new String(dp.getData(),0,dp.getLength(),"GBK"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = simpleDateFormat.format(new Date()); String content = "\t"+str; System.out.println("\n"+date); System.out.println(content); write(content,date); } catch (Exception e) { e.printStackTrace(); } } } //将对方发送内容写入文本 public void write(String content,String date) throws Exception { FileOutputStream fileOutputStream = new FileOutputStream(this.path,true); date = "\r\n"+date+"\r\n"; StringBuffer stringBuffer = new StringBuffer(date+content); String re = stringBuffer.toString(); byte[] result = re.getBytes(); fileOutputStream.write(result); fileOutputStream.close(); } }
下面附上一张运行截图(和一个有点ZZ的人一起的玩的
)

顶顶顶顶顶顶顶顶顶顶 非常不错 http://www.aomenyinzuo.cn