Greeting Server and client with Socket and ServerSocket - Java Network

Java examples for Network:ServerSocket

Description

Greeting Server and client with Socket and ServerSocket

Demo Code

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

class GreetingServer{
  private static GreetingServer server;
  static int Port = 3535;
  static ServerSocket Socket;
  
  public GreetingServer(){
    try{/* www . j  av a 2s .  c  o m*/
      Socket = new ServerSocket(setSocket());
    }catch(Exception e){
      System.out.println("Error: "+e.getMessage());
    }
  }
  
  private int setSocket(){
    Scanner in = new Scanner(System.in);
    System.out.print("Enter socket number:");
    Port = in.nextInt();
    System.out.println("Socket number "+Port+" created.");
    System.out.println("Listening...");
    return Port;
  }
  
  public static void main(String argv[]) throws Exception {
    server = new GreetingServer();
    String clientSentence;          
    String capitalizedSentence;          
    while(true){             
      Socket connectionSocket = Socket.accept();             
      BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
      DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());             
      clientSentence = inFromClient.readLine();             
      System.out.println("Received: " + clientSentence);             
      capitalizedSentence = clientSentence.toUpperCase() + " from "+Port+'\n';             
      outToClient.writeBytes(capitalizedSentence);         
    }       
  }
}

Greeting Client

Demo Code

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

public class GreetingClient
{
   public static void main(String [] args)
   {//from   ww  w  . j a  va2s .  com
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try
      {
         System.out.println("Connecting to " + serverName +
     " on port " + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Just connected to " 
     + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
         out.writeUTF("Hello from "
                      + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in =
                        new DataInputStream(inFromServer);
         System.out.println("Server says " + in.readUTF());
         client.close();
      }catch(IOException e)
      { 
         e.printStackTrace();
      }
   }
}

Related Tutorials