客户端往服务端,定时发消息通信
1.服务端
1 public class TimerServer { 2 public static void main(String[] args) throws Exception { 3 4 ServerSocket ss=new ServerSocket(1001); 5 6 7 Socket socket=ss.accept(); 8 9 10 11 InputStream is=socket.getInputStream(); 12 13 OutputStream os =socket.getOutputStream(); 14 15 16 17 //接收客户端的信息 18 byte [] buffer =new byte[1024]; 19 20 int length =0; 21 while (-1 != (length = is.read(buffer, 0, buffer.length))){ 22 String str =new String(buffer,0,length,"utf-8"); 23 System.out.println(str); 24 25 os.write(str.getBytes()); 26 os.flush(); 27 } 28 29 } 30 }
2.客户端
1 public class TimerClient { 2 public static void main(String[] args) throws Exception, Exception { 3 //新建socket端口, 4 Socket socket =new Socket("127.0.0.1",1001); 5 //new一个定时任务 并通过构造函数把socket传入 6 TimerTaskTest ttt=new TimerTaskTest(socket); 7 //新建一个计时器 8 Timer timer =new Timer (); 9 10 //每2000秒,执行定时任务ttt,初始时间是new Date(); 11 timer.schedule(ttt, new Date(),2000); 12 13 14 15 16 Timer timerfile = new Timer(); 17 18 FileTask ft=new FileTask(); 19 20 timerfile.schedule(ft,new Date(),2000); 21 } 22 23 }
3.自定义计时器任务
1 public class TimerTaskTest extends TimerTask { 2 OutputStream os = null; 3 InputStream is =null; 4 5 6 //构造函数传入socket 7 public TimerTaskTest(Socket socket ){ 8 try { 9 os = socket.getOutputStream(); 10 is = socket.getInputStream(); 11 } catch (IOException e) { 12 // TODO Auto-generated catch block 13 e.printStackTrace(); 14 } 15 16 17 } 18 19 //重载run方法 20 @Override 21 public void run() { 22 String date =new Date(System.currentTimeMillis()).toLocaleString(); 23 //打印你要的信息 24 String message =new String ("hello "+ date ); 25 try { 26 os.write(message.getBytes("utf-8")); 27 } catch (UnsupportedEncodingException e) { 28 // TODO Auto-generated catch block 29 e.printStackTrace(); 30 } catch (IOException e) { 31 // TODO Auto-generated catch block 32 e.printStackTrace(); 33 } 34 35 36 37 } 38 39 40 41 42 43 }
定时向文件写内容
4.文件计时器任务
1 public class FileTask extends TimerTask{ 2 int i=1; 3 OutputStream os =null; 4 5 //byte b []=new byte[1024]; 6 public FileTask(){ 7 try { 8 os =new FileOutputStream("E:/test/ttt.txt",true); 9 } catch (FileNotFoundException e) { 10 // TODO Auto-generated catch block 11 e.printStackTrace(); 12 } 13 14 15 } 16 17 18 @Override 19 public void run(){ 20 21 22 String str ="the "+ i+ "times to write the date \r\n"; 23 i++; 24 try { 25 os.write(str.getBytes()); 26 } catch (IOException e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 } 31 32 }