Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java TCP Connection

Tags:

java

How do I create a TCP socket in Java?

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

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

Please Help!

like image 626
user1673627 Avatar asked Sep 24 '12 11:09

user1673627


People also ask

What is TCP connection in Java?

TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.

Can Java use TCP IP?

The java.net class library provides classes Socket and ServerSocket for message passing for TCP/IP.

Does Java use TCP or UDP?

Java provides the reliable stream-based communication for TCP as well as the unreliable datagram communication for UDP.


1 Answers

How do I create a TCP socket in Java?

Socket socket = new Socket(hostname, port);

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?

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?

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.

like image 68
Peter Lawrey Avatar answered Nov 14 '22 22:11

Peter Lawrey