当前位置:   article > 正文

webSocket-简单的服务端定时推送以及重连_websocket重复推送

websocket重复推送

本文章是对webSocket的学习,在使用webSocket进行客户端-服务端的交互。

参考文章: Java基于Socket的简单推送,在文章在服务端 输入后回车 ,可进行对客户端的信息发送,同时进行回馈。

以下为自行改进:服务端定时推送信息到客户端,可根据自行需要进行调整。

说明:jdk1.8,在定时的选择,是服务端或者客户端断开可以重新连接。

Server:

  1. package demo4;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.io.OutputStreamWriter;
  9. import java.net.ServerSocket;
  10. import java.net.Socket;
  11. import java.text.SimpleDateFormat;
  12. import java.util.ArrayList;
  13. import java.util.Date;
  14. import java.util.concurrent.Executors;
  15. import java.util.concurrent.ScheduledExecutorService;
  16. import java.util.concurrent.TimeUnit;
  17. public class MyPushServer {
  18. //存储连接ip
  19. ArrayList<Socket> sockets = new ArrayList<Socket>();
  20. //定时器
  21. private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
  22. //计数
  23. private static int i=1;
  24. //主程序
  25. public static void main(String[] args) {
  26. MyPushServer myPushServer = new MyPushServer();
  27. try {
  28. myPushServer.start();
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. //程序运行
  34. public void start() throws IOException {
  35. @SuppressWarnings("resource")
  36. ServerSocket serverSocket = new ServerSocket(4000);
  37. System.out.println("服务启动成功···");
  38. while (true) {//长启动
  39. Socket socket = serverSocket.accept();
  40. System.out.println("server started... http:/"+ socket.getLocalAddress() + ":" + socket.getPort());
  41. System.out.println(socket.getLocalSocketAddress() + ":"+ socket.getLocalPort());
  42. sockets.add(socket);//添加ip列表
  43. if(i == 1){//保证只需起来一次
  44. synchronized (ServerSocket.class) {
  45. ServerThread serverThread = new ServerThread();
  46. serverThread.start();
  47. }
  48. }
  49. i++;
  50. }
  51. }
  52. //线程任务
  53. class ServerThread extends Thread {
  54. private BufferedReader reader;
  55. private BufferedWriter writer;
  56. private BufferedReader read;
  57. public ServerThread() {
  58. Runnable runnable = new Runnable() {
  59. public void run() {
  60. //发送内容-流
  61. String str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
  62. InputStream inputStream = new ByteArrayInputStream(str.getBytes());
  63. reader = new BufferedReader(new InputStreamReader(inputStream));
  64. }
  65. };
  66. // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
  67. // 第一次执行间隔为10毫秒,随后1000毫秒执行循环
  68. service.scheduleAtFixedRate(runnable, 10, 1000, TimeUnit.MILLISECONDS);
  69. }
  70. @Override
  71. public void run() {
  72. String content = null;//发送内容
  73. String getContent = null;//返回内容
  74. while (true) {
  75. try {
  76. if ((content = reader.readLine()) != null) {
  77. for (Socket socket : sockets) {
  78. System.out.println("socket:"+socket);
  79. try{
  80. socket.sendUrgentData(0xFF); //验证连接是否断开,以忽悠为一个字节的发送进行验证
  81. writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
  82. writer.write(content);
  83. writer.newLine();
  84. writer.flush();//发送
  85. read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  86. if((getContent = read.readLine()) != null) {
  87. System.out.println(getContent);
  88. }
  89. }catch(Exception ex){
  90. sockets.remove(socket);//移除断开的连接
  91. continue;
  92. }
  93. }
  94. }
  95. } catch (Exception e) {
  96. e.getStackTrace();
  97. }
  98. }
  99. }
  100. }
  101. }

Client

  1. package demo4;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStreamWriter;
  7. import java.net.Socket;
  8. import java.util.Timer;
  9. import java.util.TimerTask;
  10. public class MyPushClient {
  11. private Socket socket;
  12. public static void main(String[] args) {
  13. startConn();
  14. }
  15. /**
  16. * 长连接(可断线重连)
  17. * @Title: startConn
  18. * @Description: TODO(这里用一句话描述这个方法的作用)
  19. * @param:
  20. * @return: void
  21. * @throws
  22. */
  23. public static void startConn() {
  24. Timer timer = new Timer();
  25. TimerTask task = new TimerTask() {
  26. @Override
  27. public void run() {
  28. MyPushClient myPushClient = new MyPushClient();
  29. try {
  30. myPushClient.start();
  31. timer.cancel();
  32. System.out.println("连接成功!");
  33. } catch (Exception e1) {
  34. System.out.println("连接失败,重新连接中···");
  35. }
  36. }
  37. };
  38. long delay = 0;
  39. long intevalPeriod = 1 * 1500;
  40. timer.scheduleAtFixedRate(task, delay, intevalPeriod);
  41. }
  42. /**
  43. * 开始连接
  44. * @Title: start
  45. * @Description: TODO(这里用一句话描述这个方法的作用)
  46. * @param: @throws IOException
  47. * @return: void
  48. * @throws
  49. */
  50. public void start() throws IOException {
  51. socket = new Socket("10.200.47.222", 4000);
  52. System.out.println("server connection..");
  53. ClientThread clientThread = new ClientThread();
  54. clientThread.start();
  55. }
  56. /**
  57. * 连接线程-事件
  58. * @ClassName: ClientThread
  59. * @Description:TODO(这里用一句话描述这个类的作用)
  60. * @author: [zhu]
  61. * @date: 2017年6月12日 下午4:59:35
  62. */
  63. class ClientThread extends Thread {
  64. private BufferedReader reader;
  65. private BufferedWriter writer;
  66. public ClientThread() {
  67. try {
  68. reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  69. writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. @Override
  75. public void run() {
  76. String content = null;
  77. while (true) {
  78. try {
  79. if ((content = reader.readLine()) != null) {
  80. System.out.println(content);
  81. writer.write("收到消息");
  82. writer.newLine();
  83. writer.flush();
  84. }
  85. } catch (IOException e) {
  86. // 断线重连
  87. startConn();
  88. break;
  89. }
  90. }
  91. }
  92. }
  93. }

最后:可能会出现乱码,待解决中,会面完善会及时补上。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号