JAVA网络编程——UDP协议实现发送接收及聊天室

来源:互联网 发布:手机网页广告拦截软件 编辑:程序博客网 时间:2024/06/05 16:14

1、利用UDP协议进行发送端和接收端的消息传递

//UDPSend.javapackage UDP;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.net.UnknownHostException;public class UDPSend {    public static void main(String[] args) throws IOException {        System.out.println("发送端启动……");//        创建UDP传输的发送端//        思路://        1 建立udp的socket服务,因为接收数据 要明确端口号//        2 将要发送的数据封装到数据包中//        3 通过udp的socket服务将数据包//        4 关闭socket服务        //1 updatesocket服务 使用DatagramSocket对象        DatagramSocket ds = new DatagramSocket();        //2 将要发送的数据封装到数据包中        String str = "love guoguo";            //使用DatagramPacket将数据封装到该对象包中        byte[] buf = str.getBytes();        DatagramPacket dp =                new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.130"),8888);        //3 通过udp的socket服务将数据包发送出去,使用send方法        ds.send(dp);        //4 关闭资源        ds.close();    }}

//UDPReceive.javapackage UDP;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class UDPReceive {       public static void main(String[] args) throws IOException {             System.out.println("接收端启动……");//           建立UDP接收端的思路//           1.建立UDP socket服务//           2.创建数据包,用于存储接受到的数据,方便用户数据包的方法解析这些数据//           3.使用socket服务的receive方法将接收的数据存储到数据包中//           4.通过数据包的方法解析数据包中的数据//           5.关闭资源             //1 建立UDP socket服务             DatagramSocket ds = new DatagramSocket(8888);             //2 建立数据包             byte[] buf = new byte[1024];             DatagramPacket dp = new DatagramPacket(buf,buf.length);             //3 使用接收方法将数据存储到数据包中             ds.receive(dp);             //4 通过数据包的方法解析数据包中的数据 解析其中的数据,比如,地址、端口、数据内容             String ip = dp.getAddress().getHostAddress();             int port = dp.getPort();             String text= new String(dp.getData(),0,dp.getLength());             dp.getData();             System.out.println(ip+":"+port+":"+text);             //5 关闭资源             ds.close();       }}

也可通过CMD进行运行.class

cmd进行运行
E:\eclipse-workspace\CS\bin>java UDP.UDPReceive
E:\eclipse-workspace\CS\bin>java UDP.UDPSend

2、利用UDP协议的 发送端和接收端 加上 多线程 实现 聊天室

//Chatmain.javapackage Chatroom;import java.net.DatagramSocket;import java.net.SocketException;public class Chatmain {    public static void main(String[] args) throws SocketException {        DatagramSocket send = new DatagramSocket();        DatagramSocket rece = new DatagramSocket(8888);        new Thread(new ChatClient(send)).start();        new Thread(new ChatServer(rece)).start();    }}

//ChatClient.javapackage Chatroom;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class ChatClient  implements Runnable{    private DatagramSocket ds;    public ChatClient(DatagramSocket ds){        this.ds=ds;    }    @Override    public void run() {        // TODO Auto-generated method stub        try {            BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));            String line = null;            while((line=bufr.readLine())!=null){                byte[] buf = line.getBytes();                //使用DatagramPacket将数据封装到该对象包中                DatagramPacket dp =                        new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),8888);                ds.send(dp);                if("over".equals(line))                    break;            }        } catch (Exception e) {            // TODO: handle exception        }    }}

//ChatServer.javapackage Chatroom;import java.net.DatagramPacket;import java.net.DatagramSocket;public class ChatServer implements Runnable{    private DatagramSocket ds;    public ChatServer(DatagramSocket ds){        this.ds = ds;    }    @Override    public void run() {        // TODO Auto-generated method stub        try {            while(true){                //2 建立数据包                byte[] buf = new byte[1024];                DatagramPacket dp = new DatagramPacket(buf,buf.length);                //3 使用接收方法将数据存储到数据包中                ds.receive(dp);                //4 通过数据包的方法解析数据包中的数据 解析其中的数据,比如,地址、端口、数据内容                String ip = dp.getAddress().getHostAddress();                int port = dp.getPort();                String text= new String(dp.getData(),0,dp.getLength());                dp.getData();                System.out.println(ip+":"+port+":"+text);                if(text.equals("over")){                    System.out.println(ip+"退出聊天室");                }                //5 关闭资源                //ds.close();                }        } catch (Exception e) {            // TODO: handle exception        }    }}


1 0
原创粉丝点击