026.2 网络编程 UDP聊天

实现,通过socket对象

##############################################################
需求建立UDP发送端:
###思路:
1、建立可以实现UDP传输的socket服务
2、明确具体发送的数据
3、通过socket服务将数据发送出去
4、关闭服务

###步骤:
1、创建DatagramSocket对象
2、创建DatagramPacket对象,注意参数,(数组,数组长度,通过InetAddress.getByName("127.0.0.1")方式输入ip,端口)
3、通过DatagramSocket对象的send发送DatagramPacket对象
4、关闭DatagramSocket对象


//###发送端代码:

System.out.println("UDP发送端启动");
//1、创建UDP服务
DatagramSocket ds = new DatagramSocket();

//2、明确数据
String str = "miss";

//3、发送数据,将数据封装到数据包中
//3.1封装,明确目的和端口
byte[] buf = str.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10000);
//3.2发送
ds.send(dp);

ds.close();

##################################################################
接收端
###思路:
1、创建socket服务,明确端口
2、收数据
3、将其中需要的数据取出来,ip,端口,data
4、关闭资源

###步骤:
1、创建DatagramSocket对象
2、创建DatagramPacket对象,参数需要一个字节数组及长度
3、通过DatagramSocket对象的receive方法接收发送端发送的信息,参数填DatagramPacket对象
4、使用DatagramPacket对象的dp.getAddress().getHostAddress()方法获取IP,getPort方法获取端口
       dp.getData(),dp.getLength(),获取数据和长度
5、关闭DatagramSocket对象

//###接收端代码

System.out.println("UDP接收端启动");
//1、创建socket服务
DatagramSocket ds = new DatagramSocket(10000);

//2、使用socket的接收方法,接收数据,将接收到的数据存储到数据包中,通过数据包的方法解析
//2.1创建数据包
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
//2.2 通过数据包对象对数据解析
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();

//获取文字数据
String str = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"-"+port+":"+str);

//关闭资源
ds.close();

 

以上实现的是单发单收,不符合现实,所以要运用多线程实现多发多收
######################################################################################
以下代码,自己读一下,与多线程和流组合使用
UDP聊天多发多收代码:
#######main.java

public class UDPChatTest {
    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        /*
         * 案例一:通过udp实现群聊程序。 思路: 这个程序中既有收又有发,需要同时执行,需要使用多线程技术。
         * 一个线程负责发,一个线程负责收。需要两个任务。
         */
        //发送端的socket 接收端的socket
        DatagramSocket sendSocket = new DatagramSocket(55555);
        DatagramSocket receSocket = new DatagramSocket(10002);
        
        //创建任务对象。
        Send send = new Send(sendSocket);
        Rece rece = new Rece(receSocket);
        
        //创建线程并开启。
        Thread t1 = new Thread(send);
        Thread t2 = new Thread(rece);
        t1.start();
        t2.start();
    }
}

 

// 发送任务

class Send implements Runnable {
    private DatagramSocket ds;
    public Send(DatagramSocket ds) {
        super();
        this.ds = ds;
    }
    @Override
    public void run() {
        try {
            BufferedReader bufr = new BufferedReader(new InputStreamReader(
                    System.in));
            String line = null;
            while ((line = bufr.readLine()) != null) {
                byte[] buf = line.getBytes();// 将数据转成字节数组。
                DatagramPacket dp = new DatagramPacket(buf, buf.length,
                        InetAddress.getByName("192.168.1.223"), 10002);    //IP为255表示广播
                ds.send(dp);
                if ("886".equals(line)) {
                    break;
                }
            }

            // 4,关闭资源。
            ds.close();
        } catch (IOException e) {

        }
    }
}

 

// 接收任务。

class Rece implements Runnable {
    private DatagramSocket ds;
    public Rece(DatagramSocket ds) {
        super();
        this.ds = ds;
    }
    @Override
    public void run() {
        while (true) {
            try {
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf, buf.length);
                ds.receive(dp);// 阻塞
                
                String ip = dp.getAddress().getHostAddress();
                int port = dp.getPort();
                String text = new String(dp.getData(), 0, dp.getLength());
                System.out.println(ip + ":" + port + ":" + text);
                if(text.equals("886")){
                    System.out.println(ip+"....离开聊天室");
                }
            } catch (IOException e) {
            }
        }
    }
}

 

posted @ 2018-09-22 09:41  Alos403  阅读(320)  评论(0编辑  收藏  举报