要求實現一個聊天室,能同時接收和發送信息。java
下面的代碼用兩個線程在處理髮送和接收信息。信息在網際的傳遞採用UDP協議。這種方法不須要創建鏈接,所以比較高效,可是正因補永濟哪裏鏈接,所以會有丟包的不安全性。安全
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; //聊天室類 public class TalkingRoom { public static void main(String[] args) throws Exception { DatagramSocket sendds=new DatagramSocket(); DatagramSocket receiveds=new DatagramSocket(10001); //兩個線程,分別是發送和接收線程 new Thread(new Send(sendds)).start(); new Thread(new Recieve(receiveds)).start(); } } //發送類 class Send implements Runnable { DatagramSocket ds; public Send(DatagramSocket ds) { this.ds=ds; } public void run() { //從鍵盤按行讀入 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String line=null; try { while((line=br.readLine())!=null) { byte[] buf=line.getBytes(); DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.255"),10001); ds.send(dp); if (line.equals("over")) break; } } catch (Exception e) { } ds.close(); } } // 接收類 class Recieve implements Runnable { DatagramSocket ds; public Recieve(DatagramSocket ds) { this.ds=ds; } public void run() { while(true) { byte[] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf,buf.length); try { ds.receive(dp); } catch (Exception e) { } String ip=dp.getAddress().getHostAddress(); String text=new String(dp.getData(),0,dp.getLength()); if(text.equals("over")) System.out.print("對方已下線"); else System.out.println(ip+":"+text); } } }