码迷,mamicode.com
首页 > 编程语言 > 详细

java建立UDP连接

时间:2018-04-12 10:28:11      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:import   send   pre   add   exce   str   sock   end   客户   

1. 服务器端

package com.machuang.udp;

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

public class ServerUdp {

    public static void main(String[] args) throws IOException {
        DatagramSocket server = new DatagramSocket(8888);
        
        byte[] container = new byte[1024];
        DatagramPacket packet = new DatagramPacket(container, container.length);
        
        server.receive(packet);
        
        byte[] receiveData = packet.getData();
        int len = packet.getLength();
        System.out.println(new String(receiveData, 0, len));
        
        server.close();

    }

}

2. 客户端

package com.machuang.udp;

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

public class ClientUdp {

    public static void main(String[] args) throws IOException {
        DatagramSocket client = new DatagramSocket(6666);
        
        String msg = "请求连接服务器";
        byte[] msgBytes = msg.getBytes();
        
        DatagramPacket packet = 
                new DatagramPacket(msgBytes, msgBytes.length,  new InetSocketAddress("localhost", 8888));
        
        client.send(packet);
        
        client.close();
        
        
    }

}

 

java建立UDP连接

标签:import   send   pre   add   exce   str   sock   end   客户   

原文地址:https://www.cnblogs.com/cappuccinom/p/8805310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!