Search code examples
javasocketstcp

How to test sample TCP Socket program


I have a sample TCP client and server application that I want to run but I am not sure how to run them. It says I need to compile the client program in one host and the server application in another but I have no idea how to do this when I just have one computer. I know this is very simple but I need a little help to get me started.

Here is the sample TCP Server application:

import java.io.*; 
import java.net.*;

class TCPServer {

public static void main(String argv[]) throws Exception 
{ 
  String clientSentence; 
  String capitalizedSentence;

  ServerSocket welcomeSocket = new ServerSocket(6790); 

  while(true) { 

               Socket connectionSocket = welcomeSocket.accept();

       BufferedReader inFromClient = 
         new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

       DataOutputStream  outToClient = 
         new DataOutputStream(connectionSocket.getOutputStream());

       clientSentence = inFromClient.readLine();

       capitalizedSentence = clientSentence.toUpperCase() + '\n';

       outToClient.writeBytes(capitalizedSentence); 
    } 
} 
} 

Here is the sample TCPClient application

import java.io.*; 
import java.net.*; 
class TCPClient {

    public static void main(String argv[]) throws Exception 
    { 
        String sentence; 
        String modifiedSentence;

        BufferedReader inFromUser = 
          new BufferedReader(new InputStreamReader(System.in));

        Socket clientSocket = new Socket("10.0.1.2", 6790);

        DataOutputStream outToServer = 
          new DataOutputStream(clientSocket.getOutputStream());

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

        sentence = inFromUser.readLine();

        outToServer.writeBytes(sentence + '\n');

        modifiedSentence = inFromServer.readLine();

        System.out.println("FROM SERVER: " + modifiedSentence);

        clientSocket.close(); 
                   
    } 
}

Is something off here?

Here is exactly what I do

step1
(source: skitch.com)

step2
(source: skitch.com)

This is the first time I use Eclipse so I could be doing something wrong there. I normally use DrJava but that didn't let me run both at the same time for some reason.


Solution

  • Almost any socket program can run both halves on the same computer. Just run the server in one window, the client in another, and specify the connection address 127.0.0.1 (which means localhost, your own computer).