Skip to content
Snippets Groups Projects
DuranTcpExampleServer.java 2.68 KiB
package MV3500Cohort2022MayJune.homework2.Duran;

import MV3500Cohort2021JulySeptember.homework2.Domonique.*;
import java.io.*;
import java.net.*;


public class DuranTcpExampleServer {

    public static void main(String[] args) {
        try {
 
            System.out.println(DuranTcpExampleServer.class.getName() + " has started..."); 
            
            ServerSocket serverSocket = new ServerSocket(1414);
            OutputStream os;
            PrintStream ps;
            InetAddress localAddress, remoteAddress;
            int localPort, remotePort;
            int serverLoopCount = 0;

            while (true) { 
                
              
                try (Socket clientConnectionSocket = serverSocket.accept())
                {
                    serverLoopCount++; 
                    
                   
                    os = clientConnectionSocket.getOutputStream();
                    ps = new PrintStream(os);
                    ps.println("now " + serverLoopCount + " i am connected"); // this gets sent back to client!
                    
  
                     localAddress = clientConnectionSocket.getLocalAddress();
                    remoteAddress = clientConnectionSocket.getInetAddress();
                        localPort = clientConnectionSocket.getLocalPort();
                       remotePort = clientConnectionSocket.getPort();
                       
                    System.out.print ("Server loop " + serverLoopCount + ": ");
                    
                    
                    System.out.println(DuranTcpExampleServer.class.getName() + " socket pair showing host name, address, port:");
                    System.out.println("  (( " + 
                         localAddress.getHostName() + "=" +  localAddress.getHostAddress() + ", " + localPort + " ), ( " + 
                        remoteAddress.getHostName() + "=" + remoteAddress.getHostAddress() + ", " + remotePort + " ))");
                    
                    if ( localAddress.getHostName().equals( localAddress.getHostAddress()) ||
                        remoteAddress.getHostName().equals(remoteAddress.getHostAddress()))
                        System.out.println("  note HostName matches address if host has no DNS name");
                    
                 
                    ps.flush();
                   
                }
            }
        } catch (IOException e) {
            System.err.println("Problem with " + DuranTcpExampleServer.class.getName() + " networking: " + e);

            if (e instanceof java.net.BindException) {
                System.err.println("*** Be sure to stop any other running instances of programs using this port!");
            }
        }
    }
}