Overview
The term socket programmingrefers to writing programs that execute across multiple computers in which the devices are all connected to each other using a network. There are two communication protocols that we can use for socket programming: User Datagram Protocol (UDP) and Transfer Control Protocol (TCP). The main difference between the two is that
Project Setup
Java provides a collection of classes and interfaces that take care of low-level communication details between the client and server. These are mostly contained in the java.netpackage, so we need to make the following import: We also need the java.iopackage, which gives us input and output streams to write to and read from while communicating: For
Simple Example
Let’s get our hands dirty with the most basic of examples involving a client and a server. It’s going to be a two-way communication application where the client greets the server and the server responds. We’ll create the server application in a class called GreetServer.javawith the following code. We’ll include the mainmethod and the global variabl
How Sockets Work
We’ll use the above example to step through different parts of this section. By definition, a socket is one endpoint of a two-way communication link between two programs running on different computers on a network. A socket is bound to a port numberso that the transport layer can identify the application that data is destined to be sent to.
See full list on baeldung.com
Continuous Communication
Our current server blocks until a client connects to it, and then blocks again to listen to a message from the client. After the single message, it closes the connection because we haven’t dealt with continuity. As such, it’s only helpful in ping requests. But imagine that we’d like to implement a chat server; continuous back and forth communicatio
Server with Multiple Clients
As much as the previous example was an improvement over the first one, it’s still not a great solution. A server must have the capacity to service many clients and many requests simultaneously. Handling multiple clients is what we’re going to cover in this section. Another feature we’ll see here is that the same client could disconnect and reconnec
Conclusion
In this article, we focused on an introduction to sockets programming over TCP/IP,and wrote a simple Client/Server application in Java. The full source code for this article can be found in the GitHubproject.
See full list on baeldung.com