首頁  >  文章  >  Java  >  Java之網路程式設計實例詳解

Java之網路程式設計實例詳解

零下一度
零下一度原創
2017-07-24 09:22:521790瀏覽

一、套接字Socket

網路驅動程式提供給應用程式程式設計的介面和一種機制,可以比喻為一個港口碼頭應用程式只要把貨放在這,就算完成了貨物的運送。它在應用程式中創建,透過一種綁定機制與驅動程式建立關係,告訴自已對應的IP 和 Port。

Socket是 java 中網路程式設計的類別 , 位於java.net套件中。

---- DatagramSocket  //用於UDP通迅

---- ServerSocket //用於TCP通訊,用於服務端

---- Socket //用於Tcp通訊的服務端與客戶端

二、UDP 網路程式

InetAddress 類別  表示互聯協定(IP)位址

//static InetAddress getLocalHost()     throws UnknownHostException 傳回本機        

//static InetAddress getByName(String host) 

//static InetAddress getByName(String host) 

//static InetAddress getByName(String host) 
//static InetAddress getByName(String host) 

//static InetAddress getByName(String host) 

//static InetAddress getByName(String host) 

//static InetAddress getByName(String host) 

//static InetAddress getByName(String host) 

//static InetAddress getByName(String host) 主機名稱可為機器名稱

                                                              //(如"java.sun.com"),且可由其IP 位址的文字表示形式

//static InetAddress[] getAllByName(主機名稱傳回由其IP 位址所組成的陣列。

static void ipDemo() throws UnknownHostException{
                InetAddress netAddr=InetAddress.getLocalHost();                //取得本地电脑的一些信息System.out.println(netAddr.toString());  
                System.out.println(netAddr.getHostAddress());
                System.out.println(netAddr.getHostName()); //取得其他电脑的信息InetAddress netAddr2=InetAddress.getByName("DELL-PC");  //这里也可以传IP地址System.out.println(netAddr2.getHostAddress());  //169.254.170.71System.out.println(netAddr2.getHostName()); //DELL-PC                //取得百度的地址InetAddress []  ipList=InetAddress.getAllByName("www.baidu.com");for(InetAddress addr:ipList){
                    System.out.println(addr.toString()); 
                }
            }

三、UDP發送和接收  DatagramSocket , DatagramPacket

//例一最簡的發送和接收

發送端==要導java.net套件

透過UDP的方式把資料發出去:

#1) 建立UDPSocket服務

2) 提供資料,將資料封裝到封包中  DatagramPacket (byte[] buf, int length, InetAddress address, int port) //建構子有多個

3) 透過Socket服務,傳送資料

#4) 關閉資源

import java.net.*;class Sender4{//DatagramPacket (byte[] buf, int length, InetAddress address, int port) public static void main(String [] args) throws Exception
                                {                                      byte [] buff="hello cat".getBytes(); 
                                        DatagramSocket socket=new DatagramSocket();
                                        DatagramPacket packet=new DatagramPacket(buff,buff.length,InetAddress.getByName("192.168.0.103"),8888);
                                        socket.send(packet);
                                        socket.close();
                                        System.out.println("ok");
                                }
                            }

--接收端
1) 建立Socket服務,指定在某個連接埠上監聽
2) 建立一個用於接收資料的  DatagramPacket

3) 從套件中取出資料

4) 關閉資源

import java.net.*;class Receive4
                            {public static void main(String [] args) throws Exception
                                {
                                DatagramSocket socket=new DatagramSocket(8888); //别忘了端口号byte[] buff=new byte[1024] ;
                                    DatagramPacket packet=new DatagramPacket(buff,buff.length);
                                    
                                    socket.receive(packet);
                                    
                                    String senderIp=packet.getAddress().getHostAddress();
                                    String senderData=new String(packet.getData(),0,packet.getLength());int senderPort=packet.getPort();
                                    System.out.println(senderIp+"---"+senderData+"---"+senderPort);
                                    
                                    socket.close();
                                }
                            }
//例二,循環的發送與接收
import java.net.*;import java.io.*;class NewSender{public static void main(String [] args) throws Exception
                        {
                                System.out.println("发送端启动了");
                                DatagramSocket socket=new DatagramSocket();
                                
                                BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //包装键盘输入流String str=null;while((str=br.readLine())!=null){byte [] buff=str.getBytes();
                                        DatagramPacket packet=new DatagramPacket(buff,buff.length,InetAddress.getByName("127.0.0.1"),9000);
                                        socket.send(packet);
                                }
                                
                                br.close();
                                socket.close();            
                        }    
                    }

import java.net.*;class NewReceiver{public static void main(String [] args) throws Exception
                    {
                            DatagramSocket socket=new DatagramSocket(9000);
                            System.out.println("接收端启动了");                            while(true){ 
                                  byte [] buff=new byte[1024] ; 
                                  DatagramPacket packet=new DatagramPacket(buff,buff.length);
                                  socket.receive(packet);
                                  
                                  String senderIp=packet.getAddress().getHostAddress();                                  int sendPort=packet.getPort();
                                  String msg= new String(packet.getData(),0,packet.getLength());
                                  
                                  System.out.println(senderIp+":"+sendPort+":"+msg);    
                            }
                    }
                }
############# 例三:多執行緒聊天室程式##### # ######
class Chat
        {public static void main(String [] args)
                {new Thread(new SendThread()).start(); new Thread(new ReceiveThread()).start(); 
                }
        }
######
//发送端import java.io.*;import java.net.*;class SendThread implements Runnable
        {              private DatagramSocket socket;public void run()
                {try{
                        socket=new DatagramSocket();
                        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                        String msg=null;while((msg=br.readLine())!=null){byte[] buff=msg.getBytes();
                            DatagramPacket packet=new DatagramPacket(buff,buff.length,InetAddress.getByName("127.0.0.1"),10000);
                            socket.send(packet);
                        }
                        
                        socket.close();
                        br.close();
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                }
        }
######
//接收端import java.net.*;class ReceiveThread implements Runnable{    private DatagramSocket socket;                    public void run(){try{
                        socket=new DatagramSocket(10000);while(true){byte [] buff=new byte[1024];
                            DatagramPacket packet=new DatagramPacket(buff,buff.length);
                            socket.receive(packet);
                            
                            String senderIp=packet.getAddress().getHostAddress();int senderPort=packet.getPort();
                            String msg=new String(packet.getData(),0,packet.getLength());
                            
                            System.out.println(senderIp+":"+senderPort+":"+msg);
        
                        }
                    }catch(Exception ex)
                    {
                        System.out.println(ex.getMessage());
                    }
                }    
        }
############

以上是Java之網路程式設計實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn