zoukankan      html  css  js  c++  java
  • Java IO复习 UDP

    客户端:
    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();
            }
        }
    }

      

  • 相关阅读:
    链家新房爬虫
    豆瓣电影爬虫
    电影天堂爬虫
    数组、数组和集合的区别
    Profile小试
    SQL中的case when使用小例
    使用AVAudioPlayer播放网络音乐
    播放器
    全排列问题
    由while(scanf("%d",&n)!=EOF)引出的小问题
  • 原文地址:https://www.cnblogs.com/yunwuzhan/p/5347745.html
Copyright © 2011-2022 走看看