Monday, February 24, 2020

How to create server

The Server is a piece of program that controls every operation in the server side.
Java’s abstraction over the socket API is to use a server socket object that automatically listens, then creates a different socket on accept. Java sockets have input streams and output streams built in, which makes programming rather pleasant.

Implementing a server consists of six basic steps as follows:
  1. Create a ServerSocket object.
  2. Create a Socket object from the ServerSocket.
  3. Create an input stream to read input from the client.
  4. Create an output stream that can be used to send information back to the client.
  5. Close the Socket when done.
Following is the psuedo code for creating server for LAN based examination.

public class Server {
      public static void main(String[] args){
        try{
            int port=5555;

            ServerSocket ss=new ServerSocket(5555);
            System.out.println("Server is created...");
            while(true)
            {
                Socket s=ss.accept();//establishes connection
                System.out.println("Network is established between client and server...");
                String u,pass;
                int ID;
                DataInputStream in = new DataInputStream(s.getInputStream());
                DataOutputStream out = new DataOutputStream(s.getOutputStream());
            u = in.readUTF();
            
            pass=in.readUTF();
            Database db = new Database();
            
            System.out.println("up"+u+"  "+pass);
            ID=db.isvaliduser(u,pass);
            if( ID!=0)
            {
                System.out.println("in if");
                out.writeUTF("START");
                ServerWorker worker=new ServerWorker(s,db,ID);
                System.out.println("going into worker");
                worker.start(); 
            }else
            {
                System.out.println("in else");
                
               // errorPage();
               out.writeUTF("ABORT");
               
               out.flush();
                db.con.close();
                in.close();
                out.close();
                s.close();
            }

            }
            //System.out.println("Server diconnected successfully...");
        }catch(Exception e){System.out.println(e);}
    }
}

1. Create a ServerSocket object
With a server, you passively sit and wait for someone to come to you. So, creation requires only a port number, not a host.  
new ServerSocket(portNumber); 
On Unix, if you are a nonprivileged user, this port number must be greater than 1023 (lower  numbers are reserved) and should be greater than 5000 (numbers from 1024 to 5000 are more likely to already be in use). In addition, you should check /etc/services to make sure your selected port doesn't conflict with other services running on the same port number. If you try to listen on a socket that is already in use, an IOException will be thrown.

2. Create a Socket object from the ServerSocket 
Many servers allow multiple connections, continuing to accept connections until some termination condition is reached. The ServerSocket accept method blocks until a connection is established, then returns a normal Socket object.
    while(some condition)
   {
       Socket s=ss.accept();
       deSomethingwith(s);
    }
We have to pass this socket to a separate thread to create the input/output streams.  It efficiently handles multiple clients at once: When a client connects, the server spawns a thread, dedicated to just that client. The server can listen for and serve other clients at the same time, so we have true concurrency.

3Create an input stream to read input from the client
    DataInputStream in = new DataInputStream(s.getInputStream());   
Above code line shows the creation of an input stream.It is used before an output stream, assuming that most servers will read data before transmitting a reply. You can switch the order of this step and the next if you send data before reading, and even omit this step if your server only transmits information.

4.Create an output stream that can be used to send information back to the client
   DataOutputStream out = new DataOutputStream(s.getOutputStream());

5. Close the Socket when done
  When finished, close the socket.
      s.close();
This method closes the associated input and output streams but does not terminate any loop that listens for additional incoming connections.




Monday, February 10, 2020

Platforms for Socket Programming

Socket API is available for many languages on many platforms:

• Linux, Windows. 
1. C
2. Java
3. Perl
4. Python
5.Ruby 
The "C" language BSD API is used on Linux, all popular variants of Unix, Microsoft Windows (NT,2000,XP, and later) and even embedded OSs like VxWorks. Windows Sockets API (WSA), which was later shortened to Winsock, is a technical specification that defines how Windows network software should access network services, especially TCP/IP.
Socket Programs written in any language and running on any platform can communicate with each other! Writing communicating programs in different languages is a good exercise.

Why object oriented?
Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.
In this project we are going to use Java. Java is a general-purpose, concurrent, object-oriented, class-based, and the runtime environment(JRE) which consists of JVM which is the cornerstone of the Java platform. Java is platform independent which means that any application written on one platform can be easily ported to another platform.All the code is converted in bytecode after compilation, which is not readable by a human, and java does not use an explicit pointer and run the programs inside the sandbox to prevent any activities from untrusted sources. It enables to develop virus-free, tamper-free systems/applications. It has the ability to adapt to an evolving environment which supports dynamic memory allocation due to which memory wastage is reduced and performance of the application is increased. In addition to sockets, which can communicate with general-purpose programs in arbitrary languages, Java provides two higher-level packages for communicating with specific types of systems: Remote Method Invocation (RMI) and database connectivity (JDBC). The RMI package lets you easily access methods in remote Java objects and transfer serializable objects across network connections. JDBC lets you easily send SQL statements to remote databases. 

Tuesday, February 4, 2020

Use of TCP/IP and UDP for socket programming

Transmission Control Protocol/Internet Protocol

TCP is a standard that defines how to establish and maintain a network connection through which application programs can exchange data, and this connection is established and maintained until the application programs at each end have finished exchanging messages. TCP determines how to break application data into packets that networks can deliver, sends packets to and accepts packets from the network layer, manages flow control and because it is meant to provide error-free data transmission, it handles re-transmission of dropped or garbled packets as well as acknowledgement of all packets that arrive. TCP works with Internet Protocol(IP). IP defines how computers send data packets to each other. Together, TCP and IP are the basic rules defining the internet, they are used for organizing data in a way that ensures the secure transmission between the server and client.

Fig. TCP\IP Model Layers

On a TCP/IP network every device must have an IP address. The IP address identifies the device e.g. computer. However an IP address alone is not sufficient for running network applications, as a computer can run multiple applications and/or servicesJust as the IP address identifies the computer, The network port identifies the application or service running on the computer.The use of ports allow computers/devices to run multiple services/applications. In simple words suppose, if you use a house or apartment, IP address will correspond to the street address. All of the apartments will share the same street address. However each apartment will also have an apartment number which will correspond to the Port number.

A socket is the combination of IP address plus port, as shown in above figure.

User Defined Protocol

TCP is for connection orientated applications whereas, UDP is for connection less applications. UDP is a simple transport-layer protocol. The application writes a message to a UDP socket, which is then encapsulated in a UDP datagram, which is further encapsulated in an IP datagram, which is sent to the destination. There is no guarantee that a UDP will reach the destination, that the order of the datagrams will be preserved across the network or that datagrams arrive only once. The problem of UDP is its lack of reliability: if a datagram reaches its final destination but the checksum detects an error, or if the datagram is dropped in the network, it is not automatically retransmitted.
Applications are designed to use either the UDP or TCP transport layer protocol depending on the type of connection they require. Because there is no connection setup, UDP is faster than TCP and results in less network traffic.
Thank you!!