------- 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(),可能你們不太瞭解阻塞(阻塞指的是暫停一個線程的執行以等待某個條件的發生)。