客户端往服务端定时发送消息

来源:互联网 发布:淘宝卖百货用什么类目 编辑:程序博客网 时间:2024/06/05 02:20

服务端接收消息:

package disanzhou;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class SocketServer {
 public static void main(String[] args) throws IOException {
  ServerSocket s = new ServerSocket(1000);
  Socket socket = s.accept();
  InputStream is = socket.getInputStream();
 


  byte[] buffer = new byte[100];
  int length = 0;
  while (-1 != (length = is.read(buffer, 0, buffer.length))) {
   String str = new String(buffer, 0, length, "utf-8");
   System.out.println(str);

  }
  is.close();
  socket.close();
  s.close();
 }
}

-------------------------------------------------------------------------

 


客户端发送消息:

package disanzhou;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Timer;

public class MainTimerTask {

 public static void main(String[] args) throws Exception, IOException {
  Timer timer = new Timer();
  Socket socket = new Socket("127.0.0.1", 1000);
  timer.scheduleAtFixedRate(new MyTimerTask(socket), new Date(), 2000);

 }

}

 

-------------------------------------------------

package disanzhou;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {
 private OutputStream os;

 public MyTimerTask(Socket socket) {
  try {
   os = socket.getOutputStream();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 @Override
 public void run() {

  String date = new Date(System.currentTimeMillis()).toLocaleString();

  try {
   String message1 = new String(date);
   os.write(message1.getBytes("utf-8"));
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  try {
   os.flush();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  // System.out.println(str);
 }

}

 

0 0
原创粉丝点击