常用类构造方法 参数传递

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
}

}

}

posted on 2011-10-04 17:01  geeker  阅读(828)  评论(0编辑  收藏  举报