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)
形式的心跳包吗?如果是,那在心跳期间我怎么能发送有效的数据(假设心跳数据为无效的)呢?
阿神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)
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.