A socket connection means that two machines have information about each other’s network location IP Address and TCP port, and that they can send or receive data through the connection.
In order to create a socket server:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Main { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(5033)) { Socket socket = serverSocket.accept(); System.out.println("Client Connected" ); BufferedReader input = new BufferedReader( new InputStreamReader((socket.getInputStream()))); PrintWriter output = new PrintWriter(socket.getOutputStream(),true); while (true){ String echoString = input.readLine(); if (echoString.equals("exit")){ break; } output.println("echo from server " + echoString); } } catch (IOException e) { e.printStackTrace(); } } }
In order to create a client for the socket:
package com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class Main { public static void main(String[] args) { try (Socket socket = new Socket("localhost", 5033)) { BufferedReader echos= new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter stringToEcho= new PrintWriter(socket.getOutputStream(),true); Scanner scanner = new Scanner(System.in); String echoString; String response; do { System.out.println("Please enter a string to be echoed"); echoString = scanner.nextLine(); stringToEcho.println(echoString); if ( false== echoString.equals("exit")) { response=echos.readLine(); System.out.println(response); } }while (echoString.equals("exit")== false); } catch (IOException e) { System.out.println( "get message clent error "+ e.getMessage()); } } }