UDP傳輸:簡易聊天室的搭建。。。,udp聊天室搭建..
轉載請註明出處,謝謝:http://blog.csdn.net/harryweasley/article/details/45665309
最近看了一個教學視頻,學習socket編程,裡面有一個例子感覺寫的不錯,我就在此整理一下,協助我回憶,查看。
編寫一個聊天程式。
有收資料的部分,和發資料的部分。
這兩部分需要同時執行。
那就需要用到多線程技術。
一個線程式控制制收,一個線程式控制制發。
因為收和發動作是不一致的,所以要定義兩個run方法。
而且這兩個方法要封裝到不同的類中。
效果:
因為我這邊只有我一個電腦,所以只能我自己的這個192.168.1.48在發送資料咯~~~望見諒。。。
關於dos視窗,運行java,你可以看這個文章http://blog.csdn.net/harryweasley/article/details/45559129
/*編寫一個聊天程式。有收資料的部分,和發資料的部分。這兩部分需要同時執行。那就需要用到多線程技術。一個線程式控制制收,一個線程式控制制發。因為收和發動作是不一致的,所以要定義兩個run方法。而且這兩個方法要封裝到不同的類中。 */import java.io.*;import java.net.*;/* 定義一個udp發送端。 思路: 1,建立updsocket服務。 2,提供資料,並將資料封裝到資料包中。 3,通過socket服務的發送功能,將資料包發出去。 4,關閉資源。 */class Send implements Runnable {private DatagramSocket ds;public Send(DatagramSocket ds) {this.ds = ds;}public void run() {try {BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));String line = null;while ((line = bufr.readLine()) != null) {byte[] buf = line.getBytes();// 確定資料,並封裝成資料包。DatagramPacket(byte[] buf, int length,// InetAddress address, int port)DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.1.255"), 10002);// 通過socket服務,將已有的資料包發送出去。通過send方法。ds.send(dp);if ("886".equals(line))break;}} catch (Exception e) {throw new RuntimeException("發送端失敗");}}}/* * * 定義udp的接收端。 * 思路: 1,定義udpsocket服務。通常會監聽一個連接埠。其實就是給這個接收網路應用程式定義數位識別碼。 * 方便於明確哪些資料過來該應用程式可以處理。 * * 2,定義一個資料包,因為要儲存接收到的位元組資料。 因為資料包對象中有更多功能可以提取位元組資料中的不同資料資訊。 * 3,通過socket服務的receive方法將收到的資料存入已定義好的資料包中。 4,通過資料包對象的特有功能。將這些不同的資料取出。列印在控制台上。 * 5,關閉資源。 */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, buf.length);// 通過服務的receive方法將收到資料存入資料包中。阻塞式方法ds.receive(dp);// 通過資料包的方法擷取其中的資料。String ip = dp.getAddress().getHostAddress();String data = new String(dp.getData(), 0, dp.getLength());if ("886".equals(data)) {System.out.println(ip + "....離開聊天室");break;}System.out.println(ip + ":" + data);}} catch (Exception e) {throw new RuntimeException("接收端失敗");}}}class ChatDemo {public static void main(String[] args) throws Exception {DatagramSocket sendSocket = new DatagramSocket();// 建立udp socket,建立端點。DatagramSocket receSocket = new DatagramSocket(10002);new Thread(new Send(sendSocket)).start();new Thread(new Rece(receSocket)).start();}}
注意:InetAddress.getByName("192.168.1.255")這個意思是接收整個區域網路的資訊,是個廣播位址。
關於TCP的傳輸,你可以查看這篇文章 TCP傳輸:利用socket服務做一個文本轉換器