用Socket建立简单的C/S结构的TCP/IP服务
Java、Socket、TCP/IP、网络编程
环境:Windows Server 2003
用户也可以自己写简单的TCP/IP服务
/*作为Server建立读写二进制时间服务*/
import java.io.*;
import java.net.*;
public class DaytimeServer {
ServerSocket sock;
public DaytimeServer() {
try{
sock=new ServerSocket(37);
}
catch(IOException e){
System.err.println(e);
System.exit(1);
}
}
protected void renService() {
Socket ios = null;
DataOutputStream os = null;
while(true) {
try{
ios=sock.accept();
System.err.println(ios.getInetAddress().getHostName());
os = new DataOutputStream(ios.getOutputStream());
long time = System.currentTimeMillis();
long distance=(long)(((1970-1900)*365.25)-1+.5);
long sec=distance*24*60*60;
time /= 1000;
time += sec;
os.writeInt((int)time);
os.close();
}
catch(IOException e) {
System.err.println(e);
}
}
}
public static void main(String[] args) {
new DaytimeServer().renService();
}
}
/*读写二进制时间服务,其服务端口要保持一致,与DaytimeServer配合使用*/
import java.io.*;
import java.net.*;
import java.util.*;
public class DaytimeBinary{
public static void main(String[] args){
/*服务基于1900到现在的秒数,而JAVA为1970年,需要求时间差
*1900年减1,而1969/1970加.5*/
long distance=(long)(((1970-1900)*365.25)-1+.5);
//1900-1970的秒数
long sec=distance*24*60*60;
try{
Socket sock=new Socket("127.0.0.1",37);
DataInputStream is=new DataInputStream(new BufferedInputStream
(sock.getInputStream()));
/*服务为无符号整数,而JAVA无此类型的读入,则需要转换
*先读无符号字符型,移位,合并,组装为无符号整数*/
long remote=(((long)(is.readUnsignedByte()&0xff)<<24)|
((long)(is.readUnsignedByte()&0xff)<<16)|
((long)(is.readUnsignedByte()&0xff)<<8)|
((long)(is.readUnsignedByte()&0xff)<<0));
System.out.println("远程秒为"+remote);
System.out.println("1970-1900秒差为"+sec);
System.out.println("其差可用此值建立JAVA基于1970年对象"+(remote-sec));
System.out.println("建立ing....");
Date d=new Date((remote-sec)*1000);
System.out.println("远程时间为"+d.toString());
}
catch(IOException e){
System.err.println(e);
}
}
}