Java---Socket編程UDP/TCP

socket方便了應用程序訪問通訊協議TCP/IP 。

socket是作爲通訊鏈入的端點。我們可以吧套接字看成是電話機,有了套接字,纔有了通訊的工具。我們可以吧IP地址看成是電話號碼端口號看成是分機號

 

1、基於TCP的socket編程。

 java.net.ServerSocket是用來創建服務器端的套接字socket

 java.net.Socket是用來創建客戶端的套接字socket

 InetAddress(java.net.InetAddress)類:用來表示IP地址


凡事基於TCP創建的套接字可以叫做流套接字

 服務器端相當於一個監聽器,用來監聽端口。

 服務器與客服端之間的通訊都是輸入輸出流來實現的。

 

服務器端代碼如下:

[java] view plaincopy

  1. import java.net.*;  

  2. import java.io.*;  

  3.    

  4. class SocketTCPServer extends Thread//讓類繼承爲線程類  

  5. {  

  6.     private Socket s;  

  7.     SocketTCPServer(Socket s)  

  8.     {  

  9.         this.s = s;  

  10.     }  

  11.    

  12.     public static void main(String []args)  

  13.     {  

  14.             server();  

  15.     }  

  16.    

  17.     public void run()//這個就是線程方法了  

  18.     {  

  19.         try  

  20.         {//當然當不想直接發送數據,就會去創建一個帶緩衝的流  

  21.             OutputStream os=s.getOutputStream();  

  22.             BufferedOutputStream bos = new BufferedOutputStream(os);  

  23.             //os.write("my name is xuneng!".getBytes());  

  24.             bos.write("my name is xuneng!".getBytes());  

  25.    

  26.             InputStream is=s.getInputStream();  

  27.             byte [] buf =new byte[100];//別忘了加new  

  28.             int len=is.read(buf);  

  29.             System.out.println(new String(buf,0,len));  

  30.               

  31.             bos.close();  

  32.             is.close();  

  33.             os.close();  

  34.             s.close();  

  35.         }  

  36.         catch(Exception e)  

  37.         {  

  38.             e.printStackTrace();  

  39.         }  

  40.    

  41.     }  

  42.    

  43.     public static void server()//完成之後一定要記得關閉各種流於套接字  

  44.     {  

  45.         try  

  46.         {  

  47.             ServerSocket ss = new ServerSocket(8000);//自定義的一個端口  

  48.             while(true)//服務器端會老這樣啓動着。  

  49.             {  

  50.                 System.out.println("the server is starting .......");  

  51.                 Socket s=ss.accept();            //一直等待着接收消息  

  52.                 new SocketTCPServer(s).start();//當接受到請求的時候,就返回一個套接字,創建一個線程      

  53.             }  

  54.         }  

  55.         catch(Exception e)  

  56.         {  

  57.             e.printStackTrace();  

  58.         }  

  59.    

  60.     }  

  61.    

  62. }  


客戶端代碼如下:

[java] view plaincopy

  1. import java.net.*;  

  2. import java.io.*;  

  3.    

  4. class SocketTCPClient  

  5. {  

  6.     private Socket s;  

  7.     SocketTCPClient(Socket s)  

  8.     {  

  9.         this.s = s;  

  10.     }  

  11.    

  12.     public static void main(String []args)  

  13.     {  

  14.             client();  

  15.     }  

  16.    

  17.     public static void client()  

  18.     {  

  19.         try  

  20.         {  

  21.             Socket s = new Socket(InetAddress.getByName("localhost"),8000);//端口號要一致。  

  22.    

  23.             OutputStream os = s.getOutputStream();  

  24.             os.write("Hello World!".getBytes());  

  25.    

  26.             InputStream is = s.getInputStream();  

  27.             byte [] buf = new byte[100];  

  28.             int len = is.read(buf);  

  29.             System.out.println(new String(buf,0,len));  

  30.    

  31.             os.close();  

  32.             is.close();  

  33.             s.close();  

  34.    

  35.         }  

  36.         catch(Exception e)  

  37.         {  

  38.             e.printStackTrace();  

  39.         }  

  40.     }  

  41. }  


2、基於UDP的socket編程。 

創建流程如下:

 java.net.DatagramSocket(數據電報套接字)。

 java.net.DatagramPacket(數據電報包,裏面包含了發送的信息)。



 基於UDP的套接字就是數據報套接字

  兩個都要先構造好相應的數據包。

 DatagramPacket包中的函數 intgetLength()返回實際接受的字節數, byte[]getData()返回接受到的數據

 要想接受端給發送端回信息,就需要知道發送端IP地址InetAddress getAddress()發送端進程所綁定的端口號int getPort()

 數據報套接字發送成功之後,就相當於建立了一個虛連接,雙方可以發送數據。

 

發送端代碼如下:

[java] view plaincopy

  1. import java.net.*;  

  2. import java.io.*;  

  3. /* 

  4. *發送端, 相當於客戶端。 

  5. */  

  6. class SocketUDPSend  

  7. {  

  8.     public static void main(String[]args)  

  9.     {  

  10.             sed();  

  11.     }  

  12.    

  13.     public static void sed()  

  14.     {  

  15.         try  

  16.         {  

  17.             DatagramSocket ds = new DatagramSocket();  

  18.             String str = "haha, my name is xuneng!";  

  19.             DatagramPacket dp = new DatagramPacket(str.getBytes(),0,str.length(),  

  20.                                                 InetAddress.getByName("localhost"),8600);//發送給本機的地址,端口爲8600  

  21.                     ds.send(dp);  

  22.    

  23.             //演示接受返回回來的數據。  

  24.             byte[] buf = new byte[100];  

  25.             DatagramPacket dp2 = new DatagramPacket(buf,100);//字節數組,長度  

  26.             ds.receive(dp2);  

  27.             System.out.println(new String(buf,0,dp2.getLength()));  

  28.             ds.close();  

  29.         }  

  30.         catch(Exception e)  

  31.         {  

  32.             e.printStackTrace();  

  33.         }  

  34.     }  

  35.    

  36. }  


接收代碼如下:

[java] view plaincopy

  1. import java.net.*;  

  2. import java.io.*;  

  3. /* 

  4. *接受端,也就是服務器端。一直在監聽端口。 

  5. */  

  6. class SocketUDPRecv   

  7. {  

  8.     public static void main(String[]args)  

  9.     {  

  10.             recv();  

  11.     }  

  12.    

  13.     public static void recv()      

  14.     {  

  15.         try  

  16.         {  

  17.             DatagramSocket ds = new DatagramSocket(8600);  

  18.             byte [] buf = new byte[100];  

  19.             DatagramPacket dp = new DatagramPacket(buf,100);  

  20.             ds.receive(dp);   

  21.             System.out.println(new String(buf,0,dp.getLength()));  

  22.    

  23.         //演示給發送端返回數據,需要發送端去接受  

  24.             String str = "Yes , I received!";  

  25.             DatagramPacket dp1 = new DatagramPacket(str.getBytes(),str.length(),  

  26.                                               dp.getAddress(),dp.getPort());  

  27.             ds.send(dp1);  

  28.    

  29.             ds.close();       

  30.         }  

  31.         catch(Exception e)  

  32.         {  

  33.             e.printStackTrace();  

  34.         }  

  35.     }  

  36. }  


     轉載自:http://blog.csdn.net/xn4545945

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章