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
- JAVA test on P6multiple choice questions about java programming give you useful knowledge. if you love java programming, don't skip the series of interesting tests below by network administrator.
- Which career Java programming options are waiting for you?java programmers are experts in the java programming language. as of 2018, there are many job opportunities for java programmers. with an expected growth rate of 19% for the period 2014-2024, the career prospects for the java language are really bright.
- How to Install the Java Software Development Kitbefore you can create and modify java programs, you'll need the java software development kit. you can download the kit (also known as java sdk or jdk) for free from oracle as a single installer file, which makes installation quick and...
- How to install Java on a Raspberry Pithere are two different java implementations, oracle java and openjdk. this tutorial explains how to install java (openjdk) on a raspberry pi with the latest raspbian operating system running on it.
- How to fix the error does not install Javamore and more applications and websites require java installation before use. unfortunately, sometimes you can't install java or install it, but it doesn't work. the article will provide ways to fix errors that do not install java on your computer.
- eQuiz - Multiple choice test on Java Swing Practice - Part 2in the previous article, we introduced you to part 1 of the test of basic java swing knowledge. and below is part 2 of the quiz series with 14 questions, including some questions with many different answer options.
- How to Tune a Java Virtual Machine (JVM)the java virtual machine (jvm) runs your java programs. sometimes the default configuration that the jvm comes with may not be the most efficient for your program.
- What is the difference between Go and Java?is golang better than java? is golang harder than java? can golang replace java? this comparison will give you the answer.
- How to Fix Javajava is a computing platform that allows you to play games and view videos on your computer. you can tell that your computer is having problems with java if you see java errors appear when you try to run a program or visit a website that...
- Search and launch Java Control Panel on Windows operating systemin java control panel you can search and change java settings. in the following article, network administrator will show you how to search for java control panel on windows operating system.
- Data streams