udp通信

来源:互联网 发布:洪金宝 黑社会 知乎 编辑:程序博客网 时间:2024/05/16 18:17

package udp;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 QL {public static void main(String[] args) throws SocketException {/* * 1。需求:通过UDP实现群聊的功能; * 思路: * 这个程序中既有收又有发送的功能;需要同时执行,需要使用到多线程; * 一个线程负责发,一个线程负责收;两个任务同时执行; */     //发送端的socket 与接收端的socketDatagramSocket sendScoket=new DatagramSocket();DatagramSocket reciveScoket=new DatagramSocket(10001);// 创建任务对象Send send=new Send(sendScoket);Recive recive=new Recive(reciveScoket);//创建线程对象Thread t1=new Thread(send);Thread t2=new Thread(recive);t1.start();t2.start();}}// 发送端class Send implements Runnable{    private DatagramSocket ds;Send(DatagramSocket ds) {super();this.ds = ds;}@Overridepublic void run() {BufferedReader bufer=new BufferedReader(new InputStreamReader(System.in));String line =null;try{    while((line=bufer.readLine())!=null)     {byte buf[]=line.getBytes();//将数据转成字节数组;//将字节数据封装到数据包中DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("122.206.79.124"),10001);                       //DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("122.206.79.255"),10001);       //3.使用Socket的数据发送方法send,把数据包发送出去;ds.send(dp);            if("886".equals(line))      {     break;       }     }   } catch(IOException e){}}}//接收端class Recive implements Runnable{private DatagramSocket ds;Recive(DatagramSocket ds) {super();this.ds = ds;}@Overridepublic void run() {try{while (true){byte buf[]=new byte[1024];DatagramPacket dp= new DatagramPacket(buf, buf.length);ds.receive(dp);     //受阻;// 通过数据包对象获取发送端的信息;包括:发送端的IP,端口,发送过来的数据;String ip= dp.getAddress().getHostAddress();int port=dp.getPort();//byte text[]=dp.getData();String text =new String(dp.getData(),0,dp.getLength());System.out.println(ip+"  "+port+":"+text);if(text.equals("886")){System.out.println(ip+"离开聊天室");break;}}} catch (IOException e){} }}


原创粉丝点击