The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Networking
TCP connections
What does it mean to open a connection, and what happens if you send without one?
Why it exists — Data sent over a network can be lost on the way or arrive out of order. TCP first opens a connection to check that the other side is ready to receive, gets an acknowledgment for each piece sent and resends the piece if there is none, and puts the pieces in order by the numbers attached to them. So the program does not have to do these checks itself.
Where it's used today — A browser sending a request to a Spring Boot server on port 8080, and a Java program connecting to MySQL on port 3306 through the JDBC driver, both happen over a TCP connection. Developers rarely use Socket directly, but under what these libraries do lie the opening of a connection and the exchange of data that you see in this lab. So when a Connection refused error appears, first check whether no program is waiting on that port. Where it matters more that data arrives quickly even if a little of it is lost, as in online games or video calls, UDP is sometimes used.
TCP and UDP are two sets of rules for two programs to exchange bytes over a network, and Java provides both as classes in the java.net package. You use TCP with ServerSocket and Socket. The receiving side opens port 9000 with new ServerSocket(9000) and waits for a connection with accept(), and the sending side opens a connection with new Socket("localhost", 9000) and then writes bytes to the output stream it gets from getOutputStream(). The connection is opened only when the receiving program is waiting on that port, and the bytes sent over the opened connection arrive in the order they were sent. You use UDP with DatagramSocket and DatagramPacket. There is no line that connects; for each letter, you just send out a DatagramPacket that names where to send it, with send. In this lab you switch the way of sending between TCP and UDP, start or do not start the receiving program, and see what the two programs print. The code box shows only the lines of the main method of each program (the class and main declarations and the imports are left out), and the number 9000 is an example. localhost is a name that points to this computer itself. Port numbers and connection refusal themselves are covered in the lab "IP addresses and ports", and this lab looks at the difference between TCP, which opens a connection and then sends, and UDP, which sends without a connection.
Checked against real execution · Compiled the ServerSocket, Socket and DatagramSocket code on the screen as it is with JDK 21 (Windows 11), started the receiving side and the sending side as separate processes, ran each of the 4 combinations 5 times on localhost, and checked against the results
Concepts in this lab
- TCP and UDP
- The two main ways of transporting data on the internet. TCP establishes a connection before communication, guarantees that data arrives complete and in order, and sends data again if there is a problem. UDP sends data without a connection and does not guarantee arrival or order, but in return it is lightweight and fast. HTTP/1.1, HTTP/2, and database connections use TCP, and real-time video and voice and DNS mainly use UDP.
- TCP connection
- Where it's used today — In HTTP/1.1, a browser sends several requests one after another over one connection opened with a server. A Spring Boot server also keeps reusing a few connections opened with the database, saving the time it takes to open a connection.
- A TCP connection is what the sender and the receiver open between them before they exchange text with TCP (it is not a line that is actually laid down, but an agreement in which the operating systems on both sides remember the state of each other). The sender asks for a connection to the IP address and the port of the other side, and if a program has that port open and is waiting, the connection is opened. The procedure for opening a connection is the 3-way handshake (RFC 9293 section 3.5). After the connection is opened, TCP takes care of delivering the bytes in the order they were sent, with none missing (RFC 9293 section 2.2 says that TCP provides a reliable, in-order, byte-stream service). Without a connection, text cannot be sent. HTTP/1.1 also goes over such a reliable connection, and the default for an http address is TCP (RFC 9112 section 9). In Java, accept() of ServerSocket and the constructor of Socket meet, and one connection is opened.
- ServerSocket and Socket
- Where it's used today — Developers rarely use ServerSocket and Socket directly. The embedded web server of Spring Boot, the JDBC driver, and HTTP clients open these TCP connections and exchange data for you. Still, when you read an error such as a refused connection, knowing what these two classes do makes it easier to narrow down the cause.
- ServerSocket and Socket are classes for TCP provided by Java (in the java.net package). The receiving side opens a port with new ServerSocket(port), and when it calls accept(), it waits at that line until one connection comes. When a connection comes, accept() returns a Socket object for exchanging data over that connection. The sending side creates a Socket by giving the address and the port of the other side, as in new Socket("localhost", port), and this constructor also opens the connection. If you write to the output stream you get from getOutputStream() on a connected Socket, bytes go to the other side, and you read the bytes the other side sent from the input stream you get from getInputStream(). The other side is decided when the connection is opened, so you do not name the receiver each time you send. You close a Socket you have finished with by close().
- DatagramSocket and DatagramPacket
- Where it's used today — UDP is used where short questions and answers are exchanged quickly, as in a DNS query, and where it matters more that data is not late even if a little of it is lost, as in online games or video calls. Developers rarely use DatagramSocket directly in the code of a Java application.
- DatagramSocket and DatagramPacket are classes for UDP provided by Java (in the java.net package). DatagramSocket has neither accept() nor a constructor that opens a connection. The receiving side opens a port with new DatagramSocket(port) and waits with receive(packet) until one piece of text comes. The sending side creates new DatagramSocket(), and then sends out with send a DatagramPacket that is given the bytes to send, their length, and where to send them (an address and a port). The one piece of text sent by one send arrives as one piece with one receive. The API documentation says that each packet is sent with its own address, and that several packets can arrive in any order.
- Connection refused error
- A connection refused error is the error that the sender gets when it asks for a TCP connection but no program has that port open and is waiting. In Java, a java.net.ConnectException comes at the line new Socket, and in the check run on Windows 11 the message was "Connection refused: connect". The API documentation of ConnectException says that this exception is an error that occurred while connecting, and that it is usually a case where the connection was refused because no process is waiting at the remote address and port. The operating system of that computer refuses, and inside the same computer the error comes right away, without waiting. Because the connection was not opened, not a single piece of text is sent. The TCP standard says to send a reset signal (RST) to a request that comes with no connection (RFC 9293 section 3.5.2).
- Sending with UDP and delivery confirmation
- With UDP, you do not open a connection; each time you send text, you name where to send it (an IP address and a port) and just send it out. The UDP standard says that with this way, delivery and duplicate protection are not guaranteed (RFC 768 introduction). So when send of DatagramSocket in Java finishes without an exception, it only means that the text left this computer; it does not mean that the other side got it. In the check run, send finished without an exception even when there was no receiving program. The API documentation of send says that PortUnreachableException can be thrown only when the socket is connected to the other side with connect, and that even that is not guaranteed. To confirm delivery, you have to write code in the program yourself in which the receiver sends back an answer and the sender waits for that answer.
Try these
- Default settings — The connection is opened by accept() on the receiving side and new Socket on the sending side, and the A, B, C that were sent arrive in the order they were sent, so the receiver prints "Received: ABC".
- The receiver is not waiting — The line new Socket gets a java.net.ConnectException (Connection refused) right away, and not a single letter is sent.
- Sending with UDP — Each letter is sent with send, with no line for connecting, and the receiver gets one letter with each receive. The sender prints only "Done sending".
- Sending with UDP and no receiver — The sender prints "Done sending" without an exception and finishes. The output is the same as when the receiver is there, so the sender cannot know whether the text arrived.
Running with the default settings
- The receiving program runs the line new ServerSocket(9000). ServerSocket is a class provided by Java (java.net.ServerSocket), and this line asks the operating system, "When a TCP connection comes to port 9000 of this computer, give it to me." The sending program has not done anything yet.
- It runs the line server.accept(). accept is a method that waits until one connection comes, so the receiving program stops at this line and waits for a connection. The TCP receiver takes in a connection before it takes in any letters.
- The sending program runs the line new Socket("localhost", 9000). Socket is a class provided by Java (java.net.Socket), and this line is a request to open a TCP connection with port 9000 of localhost (this computer itself, which was 127.0.0.1 in the checking run). The line does not finish until the connection is opened or fails. None of A, B, C has been sent yet.
- A program is waiting on port 9000, so the connection is opened. The line server.accept() of the receiving side finishes and returns a Socket object for exchanging data over this connection, and the variable conn refers to that object. The line new Socket of the sending side also finishes without an exception, and the variable socket refers to the connected Socket object. Now there is one TCP connection between the two programs. The exchange of confirmations between the two operating systems when they open a connection is covered in the in-depth lab "TCP connections and retransmission".
- The sending side gets the output stream of this connection with socket.getOutputStream(), and writes A, B, C one after another with three write lines. It does not name the receiver on each line, because the other side was already decided when the connection was opened. All three finished without an exception, and after closing the connection with socket.close(), it prints "Done sending".
- The receiving side reads the bytes that came over this connection with conn.getInputStream().readAllBytes(). readAllBytes is a method that reads all the bytes that come until the other side closes the connection. The text it read is ABC, exactly in the order it was sent, and it prints "Received: ABC". TCP takes care that the bytes sent over a connection arrive in the order they were sent with none missing, and it resends a piece that is lost on the way (this lab did not cause any resending).
- What the sender got is "Done sending". With TCP, if there is no receiver, the line new Socket fails, so the fact that this line finished without an exception means that a receiving program was waiting on port 9000.
Result of this run
- You use TCP with ServerSocket and Socket. accept() on the receiving side and new Socket("localhost", 9000) on the sending side met, one connection was opened, and the A, B, C written to the output stream of that connection arrived in the order they were sent, so the receiver printed "Received: ABC".
- HTTP, which a web browser and a Spring Boot server use to talk, also goes over a TCP connection like this (RFC 9112 section 9). In the checking run, when we connected with Socket and wrote an HTTP request, the HTTP server of the JDK answered HTTP/1.1 200 OK.
Code
// Only the lines of the main method of each program are shown (the class and main declarations and the imports are left out)
// Receiving program: open port 9000 with TCP and wait for a connection
ServerSocket server = new ServerSocket(9000);
Socket conn = server.accept();
String text = new String(conn.getInputStream().readAllBytes(), "UTF-8");
System.out.println("Received: " + text);
// Sending program: connect to port 9000 of localhost with TCP, then send
Socket socket = new Socket("localhost", 9000);
OutputStream out = socket.getOutputStream();
out.write("A".getBytes("UTF-8"));
out.write("B".getBytes("UTF-8"));
out.write("C".getBytes("UTF-8"));
socket.close();
System.out.println("Done sending");
Assumptions of this model
The code on the screen was compiled as it is with JDK 21.0.12.1 (Windows 11) and actually run (verify/net/TcpBasicProbe.java). The receiving program and the sending program are separate Java processes; the lines on the screen were left as they are inside the main method, and only import java.io.OutputStream and import java.net.* were added. One line of output saying that it is ready was added to the receiving program, and the sending program was started after the receiver opened the port (this line was left out of the results). The 9000 on the screen is an example, and in the actual runs a different free number was chosen for each run, for both TCP and UDP; before starting, connecting to that number with TCP was refused every time, which confirmed that nobody had it open. The 4 combinations were run 5 times each, and the results of the 5 runs were all the same. What was checked is the standard output and the first line of the standard error and the exit code of the sender, and the standard output and the exit code of the receiver. localhost was resolved to 127.0.0.1 with InetAddress.getByName in this run. The message "Connection refused: connect" of the connection refused exception is what we saw on Windows 11, and we did not check whether the end of the message is the same on other operating systems. When new Socket("localhost", port) was run 5 times inside the same process against a port that nobody had open, ConnectException came within 1 millisecond every time, and this is short because it is inside the same computer. Whether the sender knows that a receiver is there was decided in the same way, by whether what the sender got is the same or different when the receiver was there and when it was not. TCP was different, "Done sending" against ConnectException, and UDP was the same, because it was "Done sending" in both cases. However, an opened TCP connection does not also mean a confirmation that the receiving program read the letters that were sent, and the box on the screen says only whether a receiver is there. That the letters the receiver got were in the order they were sent was observed in the checking run (inside one computer) for both ways, and the standard fixes the order only for TCP. That TCP resends when text is lost on the way was not caused in this run. As a separate check, when we started the HTTP server provided by the JDK (com.sun.net.httpserver.HttpServer), connected with Socket, and wrote the request text "GET /hello", the server received one request and answered HTTP/1.1 200 OK, and when we sent the same text to the same port with DatagramSocket, send finished without an exception but the server did not receive a request. The old version of this lab ran the same 4 combinations with net and dgram of Node.js 24.18.0 (verify/net/tcp_basic_probe.js), and then too the result was the same: for TCP a connection refused error (ECONNREFUSED), and for UDP no error even when there is no receiver. Whether the operating system actually sent a refusal signal (RST) when it refused the connection, and what signal the operating system sent back when there was no receiver in UDP, were not confirmed because we did not capture packets. From the documents, we opened and checked the following. In the API documentation of the JDK 21 source, ConnectException is an error that occurred while connecting, and it says this is usually a case where the connection was refused because no process is waiting at the remote address and port, and DatagramSocket says that each packet is sent with its own address and that several packets can arrive in any order. It says that DatagramSocket.send can throw PortUnreachableException only when the socket is connected to the other side with connect, and that even that is not guaranteed, and the sending program of this lab did not call connect. Section 2.2 of RFC 9293 (TCP) says that TCP is connection oriented and provides a reliable, in-order, byte-stream service, section 3.5 says that the procedure for opening a connection is the 3-way handshake, and section 3.5.2 says that a reset signal (RST) is sent to a request that comes with no connection. The introduction of RFC 768 (UDP) says that delivery and duplicate protection are not guaranteed in UDP. Section 9 of RFC 9112 says that HTTP assumes reliable, in-order delivery and that the default connection for an http address is TCP. This lab covers only one TCP connection and sending with UDP. It does not cover the procedure for opening and closing a connection (3-way handshake, FIN), retransmission when text is lost, putting text back in order, or flow control and congestion control. Opening a connection, retransmission, ordering, flow control, and congestion control are covered in the in-depth labs "TCP connections and retransmission" and "TCP and UDP", and closing a connection (FIN) appears there only as a single step. DatagramSocket also has a connect method, but it does not open a connection as TCP does, and it was not used here.
Previous lab: IP addresses and ports · Next lab: URLs