Results 1 to 2 of 2
  1. #1
    pi4r0n is offline Member
    Join Date
    Jan 2011
    Posts
    19
    Rep Power
    0

    Default Need advice - ServerSocket to receive 2 different types of messages.

    Hello everyone

    I have write a quick script to send CMD commands via Server Socket. I can send cmd to remote PC which is great, but I need to implement a extra print method and this is where I need your advice.

    As you can see from below main class of TCPServer has a Runtime.getRuntime().exec by which I execute a command line on the remote server. What I would also to have is a separate method which only receive a normal print commands from client and then print it out to the server.

    Can someone advice how do I achieve that ?? Do I need 2 different method 1 for sending / receiving command lines and 1 for receiving and print out if so how would I know which is being send from a client ??

    TCPServer

    Java Code:
    import java.io.BufferedReader;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.InputStream;
    import java.io.DataInputStream;
    import java.io.IOException;
    
    public class TCPServer {
    
        private static ServerSocket serverSocket = null;
        private static Socket clientSocket = null;
        private static int portNumber = 5000;
        private static BufferedReader bufferedReader;
        private static String inputLine;
    
        public static void main(String args[]) throws Exception {
    
            crateServerSocket();
    
            while (checkConnectionEstablised() == true) {
    
                System.out.println("Server connection is ready on port " + serverSocket.getLocalPort());
    
                InputStream istream = clientSocket.getInputStream();
                DataInputStream dstream = new DataInputStream(istream);
    
                String message2 = dstream.readLine();
    
                try {
                    Process process = Runtime.getRuntime().exec(message2);
                    System.out.println("Executing command: " + message2);
                } catch (IOException e) {
                    System.err.println(e);
                }
            }
        }
    
        /**
         * This method will check whether client connection have been establised
         */
        private static boolean checkConnectionEstablised() throws IOException {
            boolean connectionStatus = false;
    
            clientSocket = serverSocket.accept();
            if (true) {
                connectionStatus = true;
            } else {
                connectionStatus = false;
            }
    
            return connectionStatus;
        }
    
        /**
         * Get message from client
         */
        private static void getMessageFromClient() {
        }
    
        /**
         * This method will create a server socket 
         * and will wait for client connection
         * 
         * @return serverSocket
         */
        private static ServerSocket crateServerSocket() {
            try {
                serverSocket = new ServerSocket(portNumber);
                System.out.println("Waiting for connection");
            } catch (IOException e) {
                System.out.println("Could not listen on port: " + portNumber);
                System.out.println(e.toString());
                System.exit(-1);
            }
    
            return serverSocket;
        }
    }

    TCPClientSocket

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.SocketAddress;
    import java.net.SocketTimeoutException;
    import java.net.UnknownHostException;
    
    
    public class TCPClientSocket {
    
        private static Socket clientSocket = null;
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws UnknownHostException, IOException, Exception {
    
            clientSocket = openSocket("127.0.0.1", 5000);
    
            if (clientSocket.isConnected()) {
                
                sendMessageToServer("C:\\Windows\\notepad.exe");
    
            }
        }
    
        private static void sendMessageToServer(String msgToBeSent) throws IOException {
    
            OutputStream ostream = clientSocket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(ostream);
            dos.writeBytes(msgToBeSent);
            
            System.out.println("Message " + msgToBeSent + " has been executed sucessfuly");
    
            dos.close();
            ostream.close();
            clientSocket.close();
    
        }
    
        /*
         * Open a socket connection to the given server on the given port.
         * This method currently sets the socket timeout value to 10 seconds.
         */
        private static Socket openSocket(String server, int port) throws Exception {
            Socket socket;
    
            // create a socket with a timeout
            try {
                InetAddress inteAddress = InetAddress.getByName(server);
                SocketAddress socketAddress = new InetSocketAddress(inteAddress, port);
    
                // create a socket
                socket = new Socket();
    
                // this method will block no more than timeout ms.
                int timeoutInMs = 10 * 1000;   // 10 seconds
                socket.connect(socketAddress, timeoutInMs);
    
                return socket;
            } catch (SocketTimeoutException ste) {
                System.err.println("Timed out waiting for the socket.");
                ste.printStackTrace();
                throw ste;
            }
        }
    }
    Many thanks for in advance.

    Cheers

    pi4r0n

  2. #2
    Jhovarie is offline Banned
    Join Date
    Feb 2011
    Posts
    65
    Rep Power
    0

    Default

    Do you mean a console message if yes? try this code.

    //Server
    Java Code:
        int port = 2345;
        ServerSocket ss = new ServerSocket(port);
        while (true) {
          try {
            Socket s = ss.accept();
            String response = "Hello this is Server";
            OutputStream out = s.getOutputStream();
            out.write(response.getBytes("US-ASCII"));
            out.flush();
            s.close();
          } catch (IOException ex) {
          }
        }
    //Client
    Java Code:
    String hostname = "pcName";
        Socket theSocket = new Socket(hostname, 2345);
        BufferedReader networkIn = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
        PrintWriter out = new PrintWriter(theSocket.getOutputStream());
        System.out.println("Connected to server "+hostname);
          out.flush();
          System.out.println(networkIn.readLine());
    i think you just need a little tweak from that code.

Similar Threads

  1. send and receive text messages
    By dking in forum Networking
    Replies: 1
    Last Post: 06-21-2011, 12:53 PM
  2. Serversocket for external IP
    By Knetic in forum Networking
    Replies: 2
    Last Post: 02-16-2011, 03:32 PM
  3. ServerSocket.accept() using 100%+ CPU
    By pagod in forum Networking
    Replies: 2
    Last Post: 05-28-2010, 10:42 AM
  4. Replies: 0
    Last Post: 12-02-2008, 11:55 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •