In this example we make use of ServerSocketChannel and SocketChannel to create a simple Echo application where in the Server would print the data sent by the client.
also read:
- Java Tutorials
- Java EE Tutorials
- Design Patterns Tutorials
- Java File IO Tutorials
The code is explained with the required comments:
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Scanner; /** * This creates a server on a particular IP address and the port. * */ public class ServerClass { public static void main(String[] args) { // Create a Server socket channel. try (ServerSocketChannel serverSocket = ServerSocketChannel.open()) { // Bind the server socket channel to the IP address and Port serverSocket.bind(new InetSocketAddress("127.0.0.1", 6667)); System.out.println("Waiting for client connections"); while (true) { //Wait and Accept the client socket connection. try (SocketChannel socketChannel = serverSocket.accept()) { //Printing the address of the client. System.out.println("Obtained connection from: "+socketChannel.getRemoteAddress().toString()); //Creating a reader for reading the content on the socket input stream. Scanner socketReader = new Scanner(socketChannel.socket().getInputStream()); while(socketReader.hasNext()){ //Reading the content of the socket input stream. System.out.println(socketReader.nextLine()); } } catch(IOException ex){ ex.printStackTrace(); } } } catch (IOException ex) { ex.printStackTrace(); } } }
and the client which connects to the server is:
import java.io.IOException; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.nio.channels.SocketChannel; public class CilentClass { public static void main(String[] args) { //Create a client socket. try(SocketChannel socketChannel = SocketChannel.open()){ //Bind the client socket to the server socket. socketChannel.connect(new InetSocketAddress("127.0.0.1", 6667)); //Writing to the socket channel. PrintWriter writer = new PrintWriter(socketChannel.socket().getOutputStream(), true); writer.println("Client sending instruction 1"); writer.println("Client sending instruction 2"); writer.println("Client sending instruction 3"); writer.println("Client sending instruction 4"); }catch(IOException ex){ ex.printStackTrace(); } } }