zoukankan      html  css  js  c++  java
  • socket长连接实现


    package
    com.adao.simulater.socket; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; /** */ public class Connect { private static final ThreadLocal<Socket> threadConnect = new ThreadLocal<Socket>(); private static final String HOST = "127.0.0.1"; private static final int PORT = 8511; private static Socket client; private static OutputStream outStr = null; private static InputStream inStr = null; private static Thread tRecv = new Thread(new RecvThread()); private static Thread tKeep = new Thread(new KeepThread()); public static void connect() throws UnknownHostException, IOException { client = threadConnect.get(); if (client == null) { client = new Socket(HOST, PORT); threadConnect.set(client); tKeep.start(); System.out.println("========链接开始!========"); } outStr = client.getOutputStream(); inStr = client.getInputStream(); } public static void disconnect() { try { outStr.close(); inStr.close(); client.close(); } catch (IOException e) { e.printStackTrace(); } } private static class KeepThread implements Runnable { public void run() { try { System.out.println("=====================开始发送心跳包=============="); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("发送心跳数据包"); outStr.write("send heart beat data package !".getBytes()); } } catch (IOException e) { e.printStackTrace(); } } } private static class RecvThread implements Runnable { public void run() { try { System.out.println("==============开始接收数据==============="); while (true) { byte[] b = new byte[1024]; int r = inStr.read(b); if (r > -1) { String str = new String(b); System.out.println(str); } } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { try { Connect.connect(); tRecv.start(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

     完美

  • 相关阅读:
    Python 用 matplotlib 中的 plot 画图
    python--serial串口通信
    verilog,vhdl,bdf文件一起综合
    项目小笔记2--qt designer 修改字体,部件拖入layout,引用time模块延时,正则表达式判断输入,进制转换,部件固定大小,graphics view显示图片,消息提示框使用
    虚拟环境下通过pyinstaller 打包
    FPGA--IIC通信
    FPGA--SPI通信
    verilog 语法
    【C_Language】---队列和栈的C程序实现
    【C_Language】---C文件学习
  • 原文地址:https://www.cnblogs.com/adao21/p/13208650.html
Copyright © 2011-2022 走看看