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

Java IO复习 UDP

时间:2016-04-02 17:28:51      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

客户端:
package cn.zyw.javaurl;

import java.io.IOException;
import java.net.*;

/**
 * Created by zyw on 2016/4/2.
 */
public class UDPClient {
    public static void main(String args[]){
        try {
            DatagramSocket clientsocket=new DatagramSocket();
            String senddata="hello my name is zyw";
            byte[] bytes=senddata.getBytes();
            InetAddress ip=InetAddress.getByName("127.0.0.1");
            DatagramPacket packet=new DatagramPacket(bytes,0,senddata.length(),ip,7777);
            clientsocket.send(packet);
            byte data[]=new byte[1024];
            DatagramPacket packet1=new DatagramPacket(data,0,data.length);
            clientsocket.receive(packet1);
            String s=new String(data,0,packet1.getLength());
            System.out.println("server say:"+s);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 


服务器:
package cn.zyw.javaurl;

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

/**
 * Created by zyw on 2016/4/2.
 */
public class UDPServer {
    public static void main(String args[]){
        try {
            DatagramSocket serversocket=new DatagramSocket(7777);
            byte[] data=new byte[1024];
            DatagramPacket packet=new DatagramPacket(data,data.length);
            System.out.println("服务器已启动......");
            serversocket.receive(packet);
            String s=new String(data,0,packet.getLength());
            System.out.println("get client:"+s);

            DatagramSocket clientsocket=new DatagramSocket();
            String senddata="welcome to you visit ";
            byte[] bytes=senddata.getBytes();
            InetAddress ip=packet.getAddress();
            int port=packet.getPort();
            DatagramPacket p=new DatagramPacket(bytes,0,senddata.length(),ip,port);
            clientsocket.send(p);
        } catch (SocketException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

  

Java IO复习 UDP

标签:

原文地址:http://www.cnblogs.com/yunwuzhan/p/5347745.html

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