您的位置:首页 > 其它

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

2016-07-29 12:29 513 查看
服务端接收消息:

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);

 }

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: