DatagramSocket通訊

經常使用類構造方法 參數傳遞    DatagramPacket(byte[] buf, int length); //沒有地址信息的數據報構造器,用於接收端,等着接受無需指向地址,這個很好理解    DatagramPacket(byte[] buf,int length ,InetAddress address,int port);//有地址信息,用於發送端,發送到一個特定Ip上的特定端口上    DatagramSocket();//該Socket構造器無需制定端口號,用於發送端    DatagramSocket(int port);//該構造器用於接收端,綁定一個特定的本地端口.the port number can then be specified in a datagram packet destined for this socket.    void close();//    void receive(DatagramPacket p);    void send(DatagramPacket p);    void setSoTimeout(int timeout); //單位是秒,設定最長等待時間    //receiver.java  import java.io.IOException;  import java.net.DatagramPacket;  import java.net.DatagramSocket;  import java.net.SocketException;    public class Receiver {      /**       * @param args       */      public static void main(String[] args) {          // TODO Auto-generated method stub          try {              final int MAXLEN = 100;              byte[] buffer = new byte[MAXLEN];//字符數組初始化              //byte[] buffer=new String().getBytes();//初始化字節數組              DatagramSocket ds = new DatagramSocket(2345);//接收端初始化Socket的時候通常須要綁定一個本地端口              DatagramPacket dp = new DatagramPacket(buffer,buffer.length);              //注意DS和DP的構造方法分別有兩種,一種是參數裏面有地址信息,一種是無地址信息,好比              //DatagramSocket 接收端須要端口信息,來綁定一個本地端口,以方便發送端制定特定的端口              //而DatagramPacket得接收端不須要地址信息,而發送端則須要地址信息,這裏須要形象記憶,才能不搞混              ds.receive(dp);              int len=dp.getLength();              System.out.println(len+" bytes received.\n");              String s = new String(dp.getData(),0,len);//字節流轉化爲字符串的構造方法              System.out.println(dp.getAddress()+"at port"+dp.getPort()+" says:"+s);                        } catch (SocketException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }catch (IOException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }        }    }    //sender.java  import java.io.IOException;  import java.net.DatagramPacket;  import java.net.DatagramSocket;  import java.net.InetAddress;  import java.net.SocketException;  import java.net.UnknownHostException;    public class Sender {        /**       * @param args       */      public static void main(String[] args) {          // TODO Auto-generated method stub          try {              InetAddress receiveHost = InetAddress.getByName("localHost");//類靜態方法                                DatagramSocket theSocket = new DatagramSocket();              String message = "Hello world!";              byte[]data  = message.getBytes();              //data = theLine.getBytes();              DatagramPacket thePacket =new DatagramPacket(data,data.length,receiveHost,2345);              theSocket.send(thePacket);                    } catch (UnknownHostException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }catch (SocketException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }catch (IOException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              }                  }    }        須要總結的幾點Java小知識,    字符串轉爲整形函數:int receiverPort =  Integer.parseInt(arg[1]);    字符串轉爲字節流 byte [] buffer = message.getBytes();    字節流轉化爲字符串 String message  = new String(buffer);    字節數組初始化:byte[] buffer  = new byte[MAX_SIZE];    得到數據報的相關信息,dp.getAddress();               dp.getPort();     改進版本二    //MyDatagramSocket.java  import java.io.IOException;  import java.net.DatagramPacket;  import java.net.DatagramSocket;  import java.net.InetAddress;  import java.net.SocketException;    public class MyDatagramSocket extends DatagramSocket{      final int MAX_LEN = 100;        public MyDatagramSocket(int portNum) throws SocketException {          super(portNum);          // TODO Auto-generated constructor stub      }      public void sendMessage(InetAddress receiveHost,int receivePort,String message) throws IOException{          byte[] buffer = message.getBytes();          DatagramPacket datagram  =  new DatagramPacket(buffer,buffer.length,receiveHost,receivePort);          this.send(datagram);      }            public String receiveMessage() throws IOException{          byte[] buffer = new byte[MAX_LEN];          DatagramPacket datagram = new DatagramPacket(buffer,buffer.length);          this.receive(datagram);          String message = new String(buffer);          return message;      }    }    //ReceiverToSocket.java  import java.io.IOException;  import java.net.InetAddress;  import java.net.SocketException;  import java.net.UnknownHostException;    public class ReceiverToSender {        /**       * @param args       * @throws IOException        */      public static void main(String[] args) throws IOException {          // TODO Auto-generated method stub          if(args.length!=4)              System.out.println("Need four parameters!");          else{              InetAddress receiverHost = InetAddress.getByName(args[0]);              int receiverPort = Integer.parseInt(args[1]);              int myPort = Integer.parseInt(args[2]);              String message = args[3];                            MyDatagramSocket mds = new MyDatagramSocket(myPort);                                    System.out.println(mds.receiveMessage());//不能和下一句調換,              //由於啓動的時候先啓動這個類,receive()方法是阻塞式的,因此會              //停留在此舉,而不會發送下面的信息,另外一端還未打開,因此若是如今就              //發送的話,會出現數據報丟失現象                            mds.sendMessage(receiverHost, receiverPort, message);                            mds.close();                                      }        }    }    //SenderToReceiver.java  import java.io.IOException;  import java.net.InetAddress;  import java.net.SocketException;  import java.net.UnknownHostException;    public class SenderToReceiver {        /**       * @param args       * @throws IOException        */      public static void main(String[] args) throws IOException {          // TODO Auto-generated method stub          if(args.length!=4)              System.out.println("Need four parameters!");          else{              InetAddress receiveHost = InetAddress.getByName(args[0]);              int receivePort = Integer.parseInt(args[1]);              int myPort= Integer.parseInt(args[2]);              String message = args[3];                            MyDatagramSocket mds = new MyDatagramSocket(myPort);//此處標誌本身的端口號,由於此例子是雙向信息傳遞                            mds.sendMessage(receiveHost, receivePort, message);                            System.out.println(mds.receiveMessage());                            mds.close();//記得關閉socket          }        }    }
相關文章
相關標籤/搜索