黑馬程式員的第六天

來源:互聯網
上載者:User

 ------- android培訓、java培訓、期待與您交流! ----------

 UDP 鍵盤錄入方式資料:為了重複接收可以添加一個while(true)迴圈,但是建立DatapramSocket端服務要在while迴圈外面建立,不然是會出現*.net.bindException綁定異常的.192.168.1.255是廣播段,在這個段的所有連接埠的機器都能收到資訊。

UDP—聊天程式:

package com.four;import java.net.*;import java.io.*;/* * 編寫一個聊天程式 * 有接收資料的部分和發資料的部分 * 這兩部分需要同時執行 * 那就需要用到多線程技術 * 一個線程式控制制收,一個線程式控制制發 *  *  * 因為收和發動作是不一致的,所以要定義兩個run方法 * 而且這兩個方法要封裝到不同的類中 */public class UdpChatDemo{public static void main(String[] args) throws Exception{DatagramSocket sendSocket = new DatagramSocket();DatagramSocket receSocket = new DatagramSocket(10000);new Thread(new Send(sendSocket)).start(); new Thread(new Rece(receSocket)).start();}}class Send implements Runnable{private DatagramSocket ds;public Send(DatagramSocket ds){this.ds = ds;}public void run(){try{BufferedReader br = new BufferedReader(new InputStreamReader(System.in));String line = null;while((line=br.readLine())!=null){if("886".equals(line)){break;}byte[] buf = line.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"),10000);ds.send(dp);}}catch (Exception e){throw new RuntimeException("發送端失敗!");}}}class Rece implements Runnable{private DatagramSocket ds;public Rece(DatagramSocket ds){this.ds = ds;}public void run(){try{while(true){byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);ds.receive(dp);String ip = dp.getAddress().getHostAddress();String data = new String(dp.getData(),0,dp.getLength());System.err.println(ip+":"+data);}}catch (Exception e){throw new RuntimeException("接收端異常!");                }        }    

這個兩天程式要注意的是:有2個阻塞方法receive()和readLine(),可能你們不太瞭解阻塞(阻塞指的是暫停一個線程的執行以等待某個條件的發生)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.