Tuesday, 26 February 2013

Sample Socket Connection Example

Telnet Server Implementation Code:

class TelnetServer {
   private final ServerSocket serverSocket = new ServerSocket(4444);

   public void start(){
      try {
            log.info("Starting server on port " + serverSocket.getLocalPort());
            System.out.println("Starting server on port " + serverSocket.getLocalPort());
            while (isRunning && serverSocket != null) {
                log.info("Waiting for client connection!");
                System.out.println("Waiting for client connection!");
                Socket socket = serverSocket.accept();
                log.info("Creating new telnet client connection");
                System.out.println("Creating new client connection");
                connManager.createConnection(socket);// Create a thread to handle socket 
            }
        }
   }

}



ConnectionHandler Implementation Code:

class ConnectionHandler implements Runnable{


private final Socket socket;

public ClientConnection(){
          socket = new Socket("localhost", 4444);
}

@Override
public void run()

 try {
            iStream = new DataInputStream(socket.getInputStream());
            oStream = new DataOutputStream(socket.getOutputStream());
            out = new PrintWriter(socket.getOutputStream(), true);

            cmdContext = CommandContext.createInstance(new File("."),                               
            socket.getLocalAddress().getHostName(), socket.getInetAddress().toString());
            cmdExecutor = new CommandExecutor();
            System.out.println(cmdContext);

            while ((line = iStream.readUTF()) != null && !line.equals(".")) {
                input = input + line;
                System.out.println("Command Received: " + line);
                out.print(input);
                oStream.writeUTF(getCommandResponse(cmdContext, cmdExecutor, line));
             }
         }

    }
}

*********************************************************

TelnetClient implementation :


public class TelnetClient {
    public static void main(String args[]) throws Exception {
        Socket soc = new Socket("localhost", 4444);
        String Command;
        DataInputStream din = new DataInputStream(soc.getInputStream());
        DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Welcome to Telnet Client");
        System.out.println("< Telnet Prompt >");
        while ((Command = br.readLine()) != null && !Command.equals(".")) {
            dout.writeUTF(Command);//sends command to server
            System.out.println(din.readUTF()); //gets the response of server
        }
        soc.close();
        din.close();
        dout.close();
        br.close();
    }
}

No comments:

Post a Comment