UDP是无状态的通信方式,通过消息包进行发送通信 package cn.mym.udp;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.net.Da
package cn.mym.udp; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.util.Scanner; public class UDPUser { static Scanner sinput = new Scanner(System.in); /** *title:main
*function:UDP通信
*@author mym *@param args */ public static void main(String[] args) { new GetMsg().start(); new SendMsg().start(); } static class GetMsg extends Thread{ private DatagramSocket datagramSocket; //private ByteArrayInputStream byteArrayInputStream; //private DataInputStream dataInputStream; private byte[] bufs; private DatagramPacket p; private String msg; @Override public void run() { try { datagramSocket = new DatagramSocket(9991); bufs = new byte[1024]; p = new DatagramPacket(bufs, bufs.length); //此时数据已经存放到buf中 while(true){ /*datagramSocket.receive(p); ByteArrayInputStream bis = new ByteArrayInputStream(bufs); DataInputStream dis = new DataInputStream(bis); msg = dis.readUTF(); System.out.println("有人来信:"+msg);*/ datagramSocket.receive(p); ByteArrayInputStream bis=new ByteArrayInputStream(bufs); DataInputStream input=new DataInputStream(bis); System.out.println("有人来信:"+input.readUTF()); } } catch (Exception e) { e.printStackTrace(); } } } static class SendMsg extends Thread{ private DatagramSocket datagramSocket; private ByteArrayOutputStream bos; private DataOutputStream dos; @Override public void run() { try { datagramSocket = new DatagramSocket(9990); String ip; while(true){ bos = new ByteArrayOutputStream(); dos = new DataOutputStream(bos); String s = sinput.next(); dos.writeUTF(s); byte[] buf = bos.toByteArray(); //数据转换成字节数组 System.out.println("请输入接收数据的ip:"); ip = sinput.next(); datagramSocket.send(new DatagramPacket(buf , buf.length, new InetSocketAddress(ip,9991))); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }