0

I've just begun socket programming, and I'm working on an Echo server in Java. One of the things I'd like to do is implement the server in both TCP and UDP and allow the client to choose which protocol to use at runtime.

This is a noob question, but how do I allow a user this option to choose TCP or UDP protocols? I tried putting in an if-else at the beginning which branched on the protocol choice from scanner input, but that just skips the both blocks irrespective of the choice?

Thanks.

I've implemented the TCP echo server:

public class EchoServer 
{ 
public static void main(String[] args) throws IOException 
   { 
      ServerSocket serverSocket = null; 

      try{ 
         serverSocket = new ServerSocket(10007); 
         } 
      catch (IOException e) 
      { 
      System.err.println("Could not listen on port: 10007."); 
      System.exit(1); 
      } 

     Socket clientSocket = null; 
     System.out.println ("Waiting for connection.....");

     try { 
         clientSocket = serverSocket.accept(); 
     } 
     catch (IOException e) 
     { 
         System.err.println("Accept failed."); 
         System.exit(1); 
     } 

    System.out.println ("Connection successful");

    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), 
                                  true); 

    BufferedReader in = new BufferedReader( 
        new InputStreamReader( clientSocket.getInputStream())); 

   String cAddress = "";
   String inputLine; 

   cAddress = clientSocket.getInetAddress().toString();

   while ((inputLine = in.readLine()) != null) 
       { 
        System.out.println ("Server: " + inputLine + "  " + cAddress + " "); 
        out.println(inputLine + " " + cAddress); 

        if (inputLine.equals("bye"))            
            break;  
       } 

    out.close(); 
    in.close(); 
    clientSocket.close(); 
    serverSocket.close(); 
  } 
} 

And the client side:

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class EchoClient {
    public static void main(String[] args) throws IOException {

    Scanner s = new Scanner(System.in);  
    String serverHostname;
    System.out.println("Enter an IP value: ");
    serverHostname = s.next();

    //String serverHostname = new String ("127.0.0.1");

    if (args.length > 0)
       serverHostname = args[0];
    System.out.println ("Attemping to connect to host " +
    serverHostname + " on port 10007.");

    Socket echoSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    try {
        echoSocket = new Socket(serverHostname, 10007);
        out = new PrintWriter(echoSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(
                                    echoSocket.getInputStream()));
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host: " + serverHostname);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for "
                           + "the connection to: " + serverHostname);
        System.exit(1);
    }

BufferedReader stdIn = new BufferedReader(
                               new InputStreamReader(System.in));
String userInput;

    System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
    out.println(userInput);
    System.out.println("echo: " + in.readLine());
        System.out.print ("input: ");
}

out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
LearnHK
  • 17
  • 2
  • 6

3 Answers3

0

There is no way (that I know of) to do conditionals in Java without using the If statement. If your else-if wasn't working, then you were checking the condition wrong. To compare strings in java you use String.equals( String ), you can't use ==.

Try using it again on standard input, but just do something simple. Like:

Scanner scan = new Scanner( System.in );
System.out.println( "use tcp?" );
String in = scan.nextLine();
if( in.indexOf( "y" ) >= 0 || in.indexOf( "Y" ) >= 0 ){
    System.out.println("using tcp");
}else{
    System.out.println("not using tcp, use udp instead?");
}
VolatileDream
  • 1,083
  • 7
  • 15
  • I've tried this... but when I put the code to create the server socket and so on in if branch it just skips the entire block and executes the else branch. – LearnHK Oct 30 '11 at 18:54
  • What are you running the code from? And what happens when you execute the code I posted? – VolatileDream Oct 30 '11 at 18:59
  • I've added the code for the client side. My questions is: can I create a branch condition for the protocol choice and then include the code for the TCP and UDP protocol in the respective branch? – LearnHK Oct 30 '11 at 19:26
  • yes you can, this is usually done using functions. You'd have a function called something like `doUDP( int port )` which does udp, and another called `doTCP(int port)` which will do tcp. And then you call one or the other based off of the if statement. – VolatileDream Oct 30 '11 at 19:30
  • I tried this, but it seems that when I do this it simply skips the contents of the doTCP() function: use tcp? y not using tcp, use udp instead? – LearnHK Oct 30 '11 at 19:43
  • My mistake, code was wrong, should have been `String.indexOf(...) >= 0` and not `index > 0`. – VolatileDream Oct 30 '11 at 19:54
  • I just noticed that myself, corrected and it worked like a charm. – LearnHK Oct 30 '11 at 19:59
0

If you want to know how it is possible in the socket level, you should be able to bind your TCP serversocket and UDP serversocket in to the same port. You will have to have separate threads handling each of the sockets. For instructions how to write UDP server socket (called DatagramSocket check this tutorial.

Lycha
  • 9,937
  • 3
  • 38
  • 43
0

You need to open two separate sockets with different ports in your application. In addition to that, you need separate Threads in Java, which usage is described in a lot of how to's and tutorials.

For Socket creation use DatagramSocket for UDP and ServerSocket for TCP. I don't know, what you want to do, but you have to know that you have to handle dataloss in UDP for yourself. UDP is common used in streaming audio or video, where it is uncritical, to loss some data.

Validate your application needs. For further information see http://en.wikipedia.org/wiki/User_Datagram_Protocol#Comparison_of_UDP_and_TCP.

Your welcome.

  • Thanks mkploeppner. The thing is... I do know how to implement UDP separately but I don't know how to set up the client side to choose either protocol and make it work. – LearnHK Oct 30 '11 at 19:25
  • iirc, the udp client will use a http://download.oracle.com/javase/1.4.2/docs/api/java/net/DatagramSocket.html instead – Ray Tayek Oct 30 '11 at 20:38