package org.web.dup;
import java.io.IOException;
import java.net.*;
import java.sql.Date;
public class TimeServiceSample {
int buffersize=256;
byte buf[]=new byte[buffersize];
String data="";
int port=8080;
DatagramPacket outTimePackate;//数据报变量
DatagramSocket outTimeSocket;//DUP套接字变量
public void getConnection(){
try {
outTimeSocket= new DatagramSocket(port);
while(true){//在port出等待客户机的通信请求
outTimePackate =new DatagramPacket(buf,buf.length);
try {
outTimeSocket.receive(outTimePackate);//接受 客户机段发送的数据报
data=new Date(0).toString();//得到服务器时间
buf=data.getBytes();//转化 为字节数组
InetAddress tempAddress=outTimePackate.getAddress();//获取客户机地址
int tempport=outTimePackate.getPort();//获取客户机端口
outTimePackate=new DatagramPacket(buf,buf.length,tempAddress,tempport);//创建数据报
outTimeSocket.send(outTimePackate);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]){
new TimeServiceSample().getConnection();
}
}
package org.web.dup;
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 GetTimeSample {
int buffersize=256;
byte buf[]=new byte[buffersize];
String host="localhost";
int port=8080;
static DatagramPacket inTimePacket;
DatagramSocket inTimeSocket;//DUP套接字变量
public void connectionRecive(){
try {
InetAddress localAddress=InetAddress.getByName(host);
System.out.print("chect at"+localAddress);
inTimePacket=new DatagramPacket(buf,buf.length,localAddress,port); //创建发送到服务器段的数据报
inTimeSocket= new DatagramSocket();//创建DUP套接字变量
try {
inTimeSocket.send(inTimePacket);//发送数据报
inTimePacket=new DatagramPacket(buf,buf.length);//创建一个 用于接收的数据报
inTimeSocket.receive(inTimePacket);
String time=new String(inTimePacket.getData());
System.out.print("the time at:"+host+"is "+time);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]){
new GetTimeSample().connectionRecive();
}
}