最近在学Java,正好做一些笔记,以防止自己忘了。


client端

//UdpClient.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;


public class UdpClient {
    private static DatagramSocket clientSocket = null;
    private InetSocketAddress serverAddress = null;

    public UdpClient(String host, int port) throws SocketException {
        clientSocket = new DatagramSocket( );           //创建socket        
        serverAddress = new InetSocketAddress(host, port);  //绑定sever的ip与port
    }


    public void send(String msg) throws IOException {
        try {
            byte[] data = msg.getBytes("utf-8");   
            DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress);
            clientSocket.send(packet);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //main方法用于测试
    public static void main(String[] args) throws Exception {  
        UdpClient client = new UdpClient("127.0.0.1", 14586);
        client.send("hello world");
        clientSocket.close();
    }
}

server端

//UdpServer.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class UdpServer {
    private byte[] data = new byte[1024];
    private static DatagramSocket serverSocket = null;
    private DatagramPacket packet = null;

    public UdpServer(int port) throws SocketException {
        serverSocket = new DatagramSocket(port);
        System.out.println("sever start!");
    }

    //接收消息
    public String recieve() throws IOException {
        packet = new DatagramPacket(data, data.length);
        serverSocket.receive(packet);
        String info = new String(packet.getData(), 0, packet.getLength());
        System.out.println("recieve message from " + packet.getAddress().getHostAddress()
                + ":" + packet.getPort() + "\t"+ info);
        return info;
    }

    //本地测试
    public static void main(String[] args) throws Exception {
        UdpServer server = new UdpServer(14586);
        server.recieve();   
    }
}

打印结果

sever start!
recieve message from 127.0.0.1:64478 hello world


lifehack
134 声望6 粉丝