Java TCP 连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12563963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java TCP Connection
提问by user1673627
How do I create a TCP socket in Java?
如何在 Java 中创建 TCP 套接字?
How do I create such a TCP connection that it terminates only when I tell it to otherwise it remains open?
如何创建这样的 TCP 连接,使其仅在我告诉它时终止,否则它保持打开状态?
How do I use keepalives to know whether the server or client is still available?
如何使用 keepalives 来知道服务器或客户端是否仍然可用?
Please Help!
请帮忙!
回答by Peter Lawrey
How do I create a TCP socket in Java?
如何在 Java 中创建 TCP 套接字?
Socket socket = new Socket(hostname, port);
http://docs.oracle.com/javase/tutorial/networking/sockets/index.html
http://docs.oracle.com/javase/tutorial/networking/sockets/index.html
How do I create such a TCP connection that it terminates only when I tell it to otherwise it remains open?
如何创建这样的 TCP 连接,使其仅在我告诉它时终止,否则它保持打开状态?
They will remain open until either you or the other end closes it.
它们将保持打开状态,直到您或另一端将其关闭。
How do I use keepalives to know whether the server or client is still available?
如何使用 keepalives 来知道服务器或客户端是否仍然可用?
That is up to you. You can send different messages, one of which is a heartbeat which tells the other end you are alive.
那取决于你。您可以发送不同的消息,其中一个是心跳,告诉另一端您还活着。
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.
如果您发送二进制消息,通常要做的事情是将长度作为 unsigned short 或 int 值发送。我使用“长度”为 0 的消息作为心跳。
回答by Philipp
The class java.net.Socketis what you are searching for.
类java.net.Socket是您要搜索的内容。