Java UDP 網路編程 樣本 -Java學習筆記(30)__演算法

來源:互聯網
上載者:User

 Java UDP網路編程主要通過 DatagramSocket和DatagramPacket 兩個類實現的,下面是一個樣本程式,
Server監聽UDP 2000連接埠並把收到的Long類型數值列印出來
Client則通過輸入獲得Long類型的數值,並把它發給Server

Server: /**/ /* Coding by nyzhl */
import  java.net. * ;
import  java.io. * ;

public   class  DatagramServer  ... {
    public static void main (String[] args) ...{
        DatagramSocket ds = null;
        try ...{
            ds = new DatagramSocket(2000);
        }
        catch (SocketException e) ...{
            e.printStackTrace();
            System.exit(-1);
        }
        byte[] buffer = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
        while (true) ...{
            DataInputStream in = new DataInputStream (
                new ByteArrayInputStream (buffer)
            );
            try ...{
                ds.receive(dp);
                System.out.println(in.readLong());
                in.close();
            }
            catch (IOException e) ...{
                e.printStackTrace();
                continue;
            }
        }
        //ds.close(); JDK提示"無法訪問的語句"
        //因為前面是死迴圈,無論如何也執行不到後面的語句
    }
}

Client: /**/ /* coding by nyzhl */
import  java.net. * ;
import  java.io. * ;

public   class  DatagramClient  ... {
    public static void main (String[] args) ...{
        DatagramSocket ds = null;
        try ...{
            ds = new DatagramSocket();
        }
        catch (SocketException e) ...{
            e.printStackTrace();
            System.exit(-1);
        }
        BufferedReader typeReader = new BufferedReader (
            new InputStreamReader(System.in)
        );
        long data = 0;
        while(true) ...{
            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); 
            DataOutputStream dataOut = new DataOutputStream (bytesOut);
            try ...{
                data =<

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.