Home  >  Q&A  >  body text

java - 关于socket长连接 新手向

TCP是一种面向连接的、可靠的、基于字节流的传输层通信协议,基于TCP的socket应该也是长连接;


   public static void main(String[] args) throws IOException {
       Socket s = new Socket("127.0.0.1", 8081);
   }

我不明白一点,就是运行如上代码,会得到一个socket(假设服务器已开启),可是为什么我运行后程序会自动结束并关闭socket呢?我明明没有调用s.close(),

请问如何使程序保持长连接,只能用while(true)形式的心跳包吗?如果是,那在心跳期间我怎么能发送有效的数据(假设心跳数据为无效的)呢?

PHP中文网PHP中文网2715 days ago311

reply all(2)I'll reply

  • 阿神

    阿神2017-04-18 10:19:02

    Your code can show that the heartbeat packet is needed to maintain the connection after the thread has been recycledsocket连接。不知道你说的server是用什么开发的,如果是原生的socket,好像默认情况下并没有需要心跳包才可以维持连接,如果使用了其他框架并且设置了idle time. The server thinks that you may not connect again after being idle for a period of time, so it closes your connection to avoid wasting resources. (Personal understanding)

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:19:02

    This should be because the main thread has exited. You can add another Thread.sleep(1000000) at the end and give it a try.

    reply
    0
  • Cancelreply