码迷,mamicode.com
首页 > 其他好文 > 详细

UDPsocket编程

时间:2016-05-13 20:46:52      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

socket编程UDP模式,

package com.wtd.socket.udp;

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

public class UDPServer {
    public static void main(String[] args) {
        try {
            DatagramSocket sever= new DatagramSocket(9000);
            byte[] data= new byte[100];
            DatagramPacket dPacket= new DatagramPacket(data, 0, data.length);
            sever.receive(dPacket);
            String string= new String(data, 0, data.length);
            byte[] data2= "hello client".getBytes();
            System.out.println(dPacket.getData());
            DatagramPacket dPacket2= new DatagramPacket(data2, 0, data2.length,dPacket.getSocketAddress());
            sever.close();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
        }
        
    }
}
package com.wtd.socket.udp;

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

public class UDPClint {
    public static void main(String[] args) {
        try {
            DatagramSocket clint= new DatagramSocket();
            String str= "hello world";
            byte[] data= str.getBytes();
            DatagramPacket daPacket= new DatagramPacket(data, 0, data.length, new InetSocketAddress("127.0.0.1", 9000));
            clint.send(daPacket);
            clint.close();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

 

UDPsocket编程

标签:

原文地址:http://www.cnblogs.com/westward/p/5490914.html

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