This is a basic client/server application that allow you to send command from server to client.
Code Server:
import java.io.*; import java.net.*; public class server { public static void main(String[] args) { ServerSocket ssok = null; Socket sok = null; PrintStream ps = null; int PORT = 1111; System.out.println("Opening Socket Server......"); try { ssok = new ServerSocket(PORT); }catch(IOException e) { System.out.println("Error opening socket."); } System.out.println("Socket created......"); try{ System.out.println("Wait for connection....."); sok = ssok.accept(); }catch(IOException e) { System.out.println("Connection error."); } System.out.println("Connection succesfull...."); while(true) { try { BufferedOutputStream os = new BufferedOutputStream(sok.getOutputStream()); ps = new PrintStream(os, true); }catch(IOException e){ System.out.println("Errore"); } System.out.println("Insert a command:"); String command = reader.readString(); if(command.equals("hello")) ps.println("hello"); else if(command.equals("make")) ps.println("make"); else System.out.println("Wrong command...."); } } }
Client code:
import java.io.*; import java.net.*; public class client { public static void main(String[] args) { Socket sok = null; BufferedReader is = null; //DataInputStream.readLine is deprecated, use BufferedReader instead int PORT = 1111; try{ sok = new Socket("localhost", PORT); is = new BufferedReader(new InputStreamReader(sok.getInputStream())); }catch(IOException e) { System.out.println("Error opening socket."); } System.out.println("Socket created....."); try { String command; while((command = is.readLine()) != null) { if(command.equals("hello")) System.out.println("Hello World!!"); else if(command.equals("make")) System.out.println("make me a cake!!!"); } }catch(IOException e) { System.out.println("Reading Error"); } } }
reader is a class that help me to read inputstream.
Thank you for the attention.
RedFox