zoukankan      html  css  js  c++  java
  • SOCKET_UDP包的发送及接收

    package com.kk.review;

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;

    public class UDPServer {

    public static void main(String[] args) {
    UDPServer.receive();
    }

    static void receive(){
    try{
    DatagramSocket ds=new DatagramSocket(8890);
    byte[] buf=new byte[100];
    DatagramPacket dp=new DatagramPacket(buf,100);
    ds.receive(dp);
    String str=new String(buf,0,dp.getLength());
    System.out.println("from client:"+str);
    String str1="welcome you!";
    DatagramPacket dp1=new DatagramPacket(str1.getBytes(),str1.length(),dp.getAddress(),dp.getPort());
    ds.send(dp1);
    ds.close();
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    }
    package com.kk.review;

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;

    public class UDPClient {
    public static void main(String[] args) {
    UDPClient.send();
    }
    static void send() {
    try{
    DatagramSocket ds=new DatagramSocket();
    String str="hello udp";
    DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),InetAddress.getLocalHost(),8890);
    ds.send(dp);
    byte[] buf=new byte[100];
    DatagramPacket dp1=new DatagramPacket(buf,100);
    ds.receive(dp1);
    String str1=new String(buf,0,dp1.getLength());
    System.out.println(str1);
           ds.close();
    }catch(IOException e){
    e.printStackTrace();
    }

    }
    }



  • 相关阅读:
    C#学习笔记
    Visual Studio 快捷键
    java 8 中lambda表达式学习
    Spfa算法
    dijkstra算法
    topSort
    并查集--学习详解
    trie树--详解
    POJ1988 并查集的使用
    Mybatis的一级缓存和二级缓存
  • 原文地址:https://www.cnblogs.com/BigIdiot/p/2281260.html
Copyright © 2011-2022 走看看