使用Socket简单模拟C/S消息传递(UDP)——Java面向对象基础(32)

public class Client{
    public static final String SERVER_HOST="127.0.0.1";
    public static final int SERVER_PORT=8080;
    public static void main(String[] args) throws Exception {
        String str="你好,这里是客户端";
        byte[] bys=str.getBytes();//转化为字节数组
        //得到服务器地址
        InetAddress ia=InetAddress.getByName(SERVER_HOST);
        //构造用于发送长度的分组的数据报包 length指定主机上到指定的端口号
        DatagramPacket dp=new DatagramPacket(bys,0,bys.length,ia,SERVER_PORT);
        //创建一个用于接收或者发送的DatagramSocket -- 发射器
        DatagramSocket ds=new DatagramSocket();
        ds.send(dp);
        
    }
    
}
public class Server{
    public static final int SERVER_PORT=8080;
    public static void main(String[] args) throws Exception {
        //创建一个用于接收或者发送的DatagramSocket -- 接收器
        DatagramSocket ds=new DatagramSocket(SERVER_PORT);
        byte[] bys=new byte[1024];//用于储存接受到的信息
        //接收数据包 -- 拆包
        DatagramPacket dp=new DatagramPacket(bys,0,bys.length);
        ds.receive(dp);
        String str=new String(bys);
        System.out.println(str);
        
    }

}

 

posted @ 2020-03-25 21:37  Unlimited_Rain  阅读(196)  评论(0编辑  收藏  举报