0

I just been tasked to create a console application in C++, C# or Java language which accepts as input 1) IP address, 2) Port, 3) String and then display the string. I am not asking for any code, just some direction where I should start. Thank you.

Functionality: Program opens TCP/IP connection to specified IP and port, sends string followed with CRLF, receives everything until remote side closes connection.

Output: Program writes all received data to StdOut.

  • It's easy-peasy. In Java, on the server side, you need to create a ServerSocket object on the specific port, then a Socket object which accepts the connection from client. On the client side, you need to create a Socket object and pass to constructor server IP and a port number. I'd recommand you to use DataInputStream and DataOutputStream to read/write data. For more, see f.e. http://stackoverflow.com/questions/19839172/how-to-read-all-of-inputstream-in-server-socket-java – pzeszko Jun 27 '15 at 09:28
  • One more thing: it would work using 127.0.0.1 IP address (or simply 'localhost') when your server and client application run on the very same machine. But if you would like to try it out on two different computers (even in your local network, using IP like 192.168.xxx.xxx) it's most likely it would not work. In this case you should check your antivirus, because it usually blocks such connections. – pzeszko Jun 27 '15 at 09:35
  • I don't think the poster was asking about the server side. – Terrible Tadpole Jun 27 '15 at 09:43
  • @pzeszko my question was related to the current pc or to another pc. However, your comments can be useful. Thank you. –  Jun 27 '15 at 10:47

1 Answers1

0

This tutorial has everything you need to know, and in fact very closely matches your specificationlet:
http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html

In summary - taken from the tutorial and modified slighly to align it a little better with your requirements:

    String hostName = args [0];
    int portNumber = Integer.parseInt(args [1]);
    String transmit = args [2];

    try (
        Socket echoSocket = new Socket(hostName, portNumber);
        PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
    )
        {
            out.println(transmit);
            String response = in.readLine ();
            while (response != null) {
                System.out.println("echo: " + response);
                response = in.readLine ();
            }
        }

Hopefully that will get you started.

Terrible Tadpole
  • 605
  • 6
  • 17