How to Create a Network Application in Java
Steps
- Create a class. Create a class and name it however you want. In this article, it will be named
NetworkAppExample
.public class NetworkAppExample { }
- Create a main method. Create a main method and declare it might throw exceptions of
Exception
type and any subclass of it - all exceptions. This is considered a bad practice, but is acceptable for barebone examples.public class NetworkAppExample { public static void main(String[] args) throws Exception { } }
- Declare server address. This example will use local host address and an arbitrary port number. Port number needs to be in a range from 0 to 65535 (inclusive). However, port numbers to avoid range from 0 to 1023 (inclusive) because they are reserved system ports.
public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; } }
- Create a server. Server is bound to the address and port and listens for incoming connections. In Java,
ServerSocket
represents server-side endpoint and its function is accepting new connections.ServerSocket
does not have streams for reading and sending data because it does not represent connection between a server and a client.import java.net.InetAddress; import java.net.ServerSocket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); } }
- Log server inception. For logging purposes, print to the console that server has been started.
import java.net.InetAddress; import java.net.ServerSocket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); } }
- Create a client. Client is bound to the address and port of a server and listens for packets (messages) after connection is established. In Java,
Socket
represents either a client-side endpoint connected to the server or a connection (from server) to client and is used to communicate with the party on the other end.import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); } }
- Log connection attempt. For logging purposes, print to the console that connection has been attempted.
import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); } }
- Establish connection. Clients will never connect unless server listens for and accepts, in other words establishes, connections. In Java, connections are established using
accept()
method ofServerSocket
class. The method will block execution until a client connects.import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); } }
- Log established connection. For logging purposes, print to the console that connection between server and client has been established.
import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); } }
- Prepare communication streams. Communication is done over streams and, in this application, raw streams of (connection from) server (to client) and client need to be chained to either data or object streams. Remember, both parties need to use the same stream type.
- Data streams
import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); DataOutputStream clientOut = new DataOutputStream(client.getOutputStream()); DataInputStream clientIn = new DataInputStream(client.getInputStream()); DataOutputStream serverOut = new DataOutputStream(connection.getOutputStream()); DataInputStream serverIn = new DataInputStream(connection.getInputStream()); } }
- Object streams
When multiple object streams are used, input streams have to be initialized in the same order as output streams becauseObjectOutputStream
sends a header to the other party andObjectInputStream
blocks execution until it reads the header.import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); ObjectOutputStream clientOut = new ObjectOutputStream(client.getOutputStream()); ObjectOutputStream serverOut = new ObjectOutputStream(connection.getOutputStream()); ObjectInputStream clientIn = new ObjectInputStream(client.getInputStream()); ObjectInputStream serverIn = new ObjectInputStream(connection.getInputStream()); } }
Order as specified in the code above might be easier to remember - first initialize output streams then input streams in the same order. However, another order for initialization of object streams is the following:
ObjectOutputStream clientOut = new ObjectOutputStream(client.getOutputStream()); ObjectInputStream serverIn = new ObjectInputStream(connection.getInputStream()); ObjectOutputStream serverOut = new ObjectOutputStream(connection.getOutputStream()); ObjectInputStream clientIn = new ObjectInputStream(client.getInputStream());
- Data streams
- Log that communication is ready. For logging purposes, print to the console that communication is ready.
// code omitted import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); // code omitted System.out.println("Communication is ready."); } }
- Create a message. In this application,
Hello World
text will be sent to the server either asbyte[]
orString
. Declare a variable of the type that depends on the stream used. Usebyte[]
for data streams andString
for object streams.- Data streams
Using data streams, serialization is done by converting objects into primitive data types or aString
. In this case,String
is converted tobyte[]
instead of written usingwriteBytes()
method to show how it would be done with other objects, such as images or other files.import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); DataOutputStream clientOut = new DataOutputStream(client.getOutputStream()); DataInputStream clientIn = new DataInputStream(client.getInputStream()); DataOutputStream serverOut = new DataOutputStream(connection.getOutputStream()); DataInputStream serverIn = new DataInputStream(connection.getInputStream()); System.out.println("Communication is ready."); byte[] messageOut = "Hello World".getBytes(); } }
- Object streams
import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); ObjectOutputStream clientOut = new ObjectOutputStream(client.getOutputStream()); ObjectOutputStream serverOut = new ObjectOutputStream(connection.getOutputStream()); ObjectInputStream clientIn = new ObjectInputStream(client.getInputStream()); ObjectInputStream serverIn = new ObjectInputStream(connection.getInputStream()); System.out.println("Communication is ready."); String messageOut = "Hello World"; } }
- Data streams
- Send the message. Write data to the output stream and flush the stream to ensure the data has been written entirely.
- Data streams
Length of a message needs to be sent first so the other party knows how many bytes it needs to read. After the length is sent as a primitive integer type, bytes can be sent.import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); DataOutputStream clientOut = new DataOutputStream(client.getOutputStream()); DataInputStream clientIn = new DataInputStream(client.getInputStream()); DataOutputStream serverOut = new DataOutputStream(connection.getOutputStream()); DataInputStream serverIn = new DataInputStream(connection.getInputStream()); System.out.println("Communication is ready."); byte[] messageOut = "Hello World".getBytes(); clientOut.writeInt(messageOut.length); clientOut.write(messageOut); clientOut.flush(); } }
- Object streams
import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); ObjectOutputStream clientOut = new ObjectOutputStream(client.getOutputStream()); ObjectOutputStream serverOut = new ObjectOutputStream(connection.getOutputStream()); ObjectInputStream clientIn = new ObjectInputStream(client.getInputStream()); ObjectInputStream serverIn = new ObjectInputStream(connection.getInputStream()); System.out.println("Communication is ready."); String messageOut = "Hello World"; clientOut.writeObject(messageOut); clientOut.flush(); } }
- Data streams
- Log sent message. For logging purposes, print to the console that message has been sent.
- Data streams
import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); DataOutputStream clientOut = new DataOutputStream(client.getOutputStream()); DataInputStream clientIn = new DataInputStream(client.getInputStream()); DataOutputStream serverOut = new DataOutputStream(connection.getOutputStream()); DataInputStream serverIn = new DataInputStream(connection.getInputStream()); System.out.println("Communication is ready."); byte[] messageOut = "Hello World".getBytes(); clientOut.writeInt(messageOut.length); clientOut.write(messageOut); clientOut.flush(); System.out.println("Message sent to server: " + new String(messageOut)); } }
- Object streams
import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class NetworkAppExample { public static void main(String[] args) throws Exception { String host = "localhost"; int port = 10430; ServerSocket server = new ServerSocket(port, 50, InetAddress.getByName(host)); System.out.println("Server started."); Socket client = new Socket(host, port); System.out.println("Connecting to server..."); Socket connection = server.accept(); System.out.println("Connection established."); ObjectOutputStream clientOut = new ObjectOutputStream(client.getOutputStream()); ObjectOutputStream serverOut
5 ★ | 1 VoteYou should read it
- Basic Java syntax
- What is JAVA file? How to open, edit and convert JAVA files
- eQuiz - Multiple choice quiz about JAVA
- Download and install Java on the computer
- Basic Java exercises, with sample decoding
- Which career Java programming options are waiting for you?
- How to install Java on a Raspberry Pi
- How to fix the error does not install Java
May be interested
- How to Download Eclipseeclipse is a open-source application made by the eclipse foundation to help you write java better and it has become the most popular java editor. if you are having trouble getting eclipse for your system here's how you do it. head to the...
- How to Create a Swing GUI in Javathis article explains how to create simple application that is shown in the figure on the right, giving its source code as well. to place buttons, text labels and other components on the program window, you need to understand about jpanel....
- How to Disable Javajava is a popular programming language and platform for dynamic or interactive websites and web applications. however, java can consume a lot of memory on your device or cause your browser to perform slower than expected. security issues...
- How to Manipulate Strings in Javastrings are sequences of characters. for example, 'hello!' is a string because it is made up of the characters 'h', 'e', 'l', 'l', 'o', and '!'. in java, strings are objects, which means that there is a string class that has fields and...
- How to Set Up a Java Programming Environmentjava is a popular and long-standing programming language, used by large and small, new and old companies alike. setting up your computer to run java for the first time can be a mild hassle. this wikihow will detail how to configure the...
- How to Make a GUI Grid in Javathe grid does nothing special at this stage, but with a little bit of research, you can add action listeners and a bit of logic to make a simple 2d game like tic-tac-toe, or more complicated ones like battleship. note: this article uses...
- Data streams