Java TCP连接

Java TCP连接

问题描述:

如何在Java中创建TCP套接字?

How do I create a TCP socket in Java?

我如何创建这样的TCP连接,使其仅在我告诉它时才终止,否则它将保持打开状态?

How do I create such a TCP connection that it terminates only when I tell it to otherwise it remains open?

我如何使用Keepalive来了解服务器或客户端是否仍然可用?

How do I use keepalives to know whether the server or client is still available?

请帮助!

如何在Java中创建TCP套接字?

How do I create a TCP socket in Java?

Socket socket = new Socket(hostname, port);

http://docs.oracle.com/javase/tutorial/联网/sockets/index.html

我如何创建这样的TCP连接,使其仅在我告诉它时才终止,否则它将保持打开状态?

How do I create such a TCP connection that it terminates only when I tell it to otherwise it remains open?

它们将保持打开状态,直到您或另一端将其关闭为止.

They will remain open until either you or the other end closes it.

我如何使用Keepalive来了解服务器或客户端是否仍然可用?

How do I use keepalives to know whether the server or client is still available?

由您决定.您可以发送不同的消息,其中之一是心跳,告诉您您还活着.

That is up to you. You can send different messages, one of which is a heartbeat which tells the other end you are alive.

如果要发送二进制消息,通常要做的是将长度作为无符号的short或int值发送.我将"length" 0的消息用作心跳.

A common thing to do if you are sending binary messages is to send the length as an unsigned short or int value. I use a message of "length" 0 as a heartbeat.