udp通信

xiaoxiao2021-02-28  124

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 与接收端的socket DatagramSocket 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; } @Override public 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; } @Override public 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){} } }

转载请注明原文地址: https://www.6miu.com/read-22385.html

最新回复(0)