阿赞 2011-10-12
1:客户端程序
viewplain
packagecom.pb.udp;
importjava.io.IOException;
importjava.net.DatagramPacket;
importjava.net.InetAddress;
importjava.net.UnknownHostException;
importjava.net.DatagramSocket;
/**
*使用Sender类来代表客户端程序,
*@authorccna_zhang
*
*/
publicclassSender{
publicstaticvoidmain(String[]args){
Stringmsg="Hello,World";
byte[]buf=msg.getBytes();
try{
InetAddressaddress=InetAddress.getByName("192.168.1.80");//服务器地址
intport=8080;//服务器的端口号
//创建发送方的数据报信息
DatagramPacketdataGramPacket=newDatagramPacket(buf,buf.length,address,port);
DatagramSocketsocket=newDatagramSocket();//创建套接字
socket.send(dataGramPacket);//通过套接字发送数据
//接收服务器反馈数据
byte[]backbuf=newbyte[1024];
DatagramPacketbackPacket=newDatagramPacket(backbuf,backbuf.length);
socket.receive(backPacket);//接收返回数据
StringbackMsg=newString(backbuf,0,backPacket.getLength());
System.out.println("服务器返回的数据为:"+backMsg);
socket.close();
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
2:服务器端程序
viewplain
packagecom.pb.udp;
importjava.io.IOException;
importjava.net.DatagramPacket;
importjava.net.DatagramSocket;
importjava.net.InetAddress;
importjava.net.SocketAddress;
importjava.net.UnknownHostException;
/**
*服务器端程序
*@authorccna_zhang
*
*/
publicclassReceiver{
publicstaticvoidmain(String[]args){
try{
InetAddressaddress=InetAddress.getLocalHost();
intport=8080;
//创建DatagramSocket对象
DatagramSocketsocket=newDatagramSocket(port,address);
byte[]buf=newbyte[1024];//定义byte数组
DatagramPacketpacket=newDatagramPacket(buf,buf.length);//创建DatagramPacket对象
socket.receive(packet);//通过套接字接收数据
StringgetMsg=newString(buf,0,packet.getLength());
System.out.println("客户端发送的数据为:"+getMsg);
//从服务器返回给客户端数据
InetAddressclientAddress=packet.getAddress();//获得客户端的IP地址
intclientPort=packet.getPort();//获得客户端的端口号
SocketAddresssendAddress=packet.getSocketAddress();
Stringfeedback="Received";
byte[]backbuf=feedback.getBytes();
DatagramPacketsendPacket=newDatagramPacket(backbuf,backbuf.length,sendAddress);//封装返回给客户端的数据
socket.send(sendPacket);//通过套接字反馈服务器数据
socket.close();//关闭套接字
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
3:程序运行结果
服务器端:
客户端发送的数据为:Hello,World
客户端:
服务器返回的数据为:Received