Home

Implement client-server communication using TCP

Implement client-server communication using TCP

Introduction:
                       TCP provides the service of exchanging data directly between two network hosts, whereas IP handles addressing and routing message across one or more networks. In particular, TCP provides reliable, ordered delivery of a stream of bytes from a program on one computer to another program on another computer. TCP is the protocol that major Internet applications rely on, applications such as the World Wide Web, e-mail, and file transfer.
                       TCP connection is managed by an operating system through a programming interface that represents the local end-point for communications, the Internet socket. During the lifetime of a TCP connection it undergoes a series of state changes:


  1. LISTEN : In case of a server, waiting for a connection request from any remote client.
  2. SYN-SENT : waiting for the remote peer to send back a TCP segment with the SYN and ACK flags set. (usually set by TCP clients)
  3. SYN-RECEIVED : waiting for the remote peer to send back an acknowledgment after having sent back a connection acknowledgment to the remote peer. (usually set by TCP servers)
  4. ESTABLISHED : the port is ready to receive/send data from/to the remote peer.
  5. FIN-WAIT-1
  6. FIN-WAIT-2
  7. CLOSE-WAIT
  8. CLOSING
  9. LAST-ACK
  10. TIME-WAIT : represents waiting for enough time to pass to be sure the remote peer received the acknowledgment of its connection termination request. According to RFC 793 a connection can stay in TIME-WAIT for a maximum of four minutes.
  11. CLOSED

TCP uses the notion of port numbers to identify sending and receiving application end-points on a host, or Internet sockets. Each side of a TCP connection has an associated 16-bit unsigned port number (0-65535) reserved by the sending or receiving application. Arriving TCP data packets are identified as belonging to a specific TCP connection by its sockets, that is, the combination of source host address, source port, destination host address, and destination port. This means that a server computer can provide several clients with several services simultaneously, as long as a client takes care of initiating any simultaneous connections to one destination port from different source ports.


TCP Server:
import java.net.*;
import java.io.*;

public class TCPServer  {
   public static void main(String a[])
   {
      Socket s=null;
      try
      {
int serverPort=8117;
ServerSocket listenSocket=new ServerSocket(serverPort);
while(true)
{
   Socket clientSocket=listenSocket.accept();
   Connection c=new Connection(clientSocket);
}
      }
      catch(IOException e)
      {   System.out.println("Listen:"+e.getMessage());   }
   }
}

class Connection extends Thread  {
   DataInputStream in;
   DataOutputStream out;
   Socket clientSocket;
   public Connection(Socket aClientSocket)  {
      try      {
clientSocket=aClientSocket;
in=new DataInputStream(clientSocket.getInputStream());
out=new DataOutputStream(clientSocket.getOutputStream());
this.start();
      }
      catch(IOException e)
      {
System.out.println("Connection:"+e.getMessage());
      }
   }
   public void run()  {
      try  {
String data=in.readUTF();
out.writeUTF(data);
      }
      catch(EOFException e)
      {   System.out.println("EOF:"+e.getMessage());   }
      catch(IOException e)
      {   System.out.println("IO:"+e.getMessage());   }
      finally
      {
try
{
   clientSocket.close();
}
catch(IOException e)
{   System.out.println("IO:"+e.getMessage());   }
      }
   }
}
TCP Client:

import java.net.*;
import java.io.*;
public class TCPClient {
            public static void main (String args[]) {
                        // arguments supply message and hostname
                        Socket s = null;
                        try{
                                    int serverPort = 8117;
                                    s = new Socket(args[1], serverPort);   
                                    DataInputStream in = new DataInputStream( s.getInputStream());
                                    DataOutputStream out =new DataOutputStream( s.getOutputStream());
                                    out.writeUTF(args[0]);            // UTF is a string encoding see Sn. 4.4
                                    String data = in.readUTF();        // read a line of data from the stream
                                    System.out.println("Received: "+ data) ;
                        }catch (UnknownHostException e){System.out.println("Socket:"+e.getMessage());
                        }catch (EOFException e){System.out.println("EOF:"+e.getMessage());
                        }catch (IOException e){System.out.println("readline:"+e.getMessage());
                        }finally {if(s!=null) try {s.close();}catch (IOException e){System.out.println("close:"+e.getMessage());}}
     }
}


TCP: OUTPUT
C:\Documents and Settings\cse4y>e:
E:\>cd Lab
E:\Lab>cd TCP
E:\Lab\TCP>javac *.java
E:\Lab\TCP>java TCPServer 127.0.0.1

C:\Documents and Settings\cse4y>e:
E:\>cd Lab
E:\Lab>cd TCP
E:\Lab\TCP>java TCPClient hello 127.0.0.1
received;hello

Implement client-server communication using UDP

Implement client-server communication using UDP

Introduction:
           With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network without requiring prior communications to set up special transmission channels or data paths. UDP uses a simple transmission model without implicit hand-shaking  for providing reliability, ordering, or data integrity. UDP's stateless nature is also useful for servers answering small queries from huge numbers of clients. Unlike TCP, UDP is compatible with packet broadcast (sending to all on local network) and multicasting (send to all subscribers).

                       Common network applications that use UDP include  the Domain Name System (DNS).

           UDP applications use datagram sockets to establish host-to-host communications. A Datagram socket is a type of Internet socket, which is the sending or receiving point for packet delivery services.[1] Each packet sent or received on a Datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may arrive in any order and might not arrive at the receiving computer.UDP broadcasts sends are always enabled on a Datagram Socket. In order to receive broadcast packets a Datagram Socket must be bound to a more specific address.

            An application binds a socket to its endpoint of data transmission, which is a combination of an IP address and a service port. A port is a software structure that is identified by the port number, a 16 bit integer value, allowing for port numbers between 0 and 65535.

Port numbers are divided into three ranges:
·         Port numbers 0 through 1023 are used for common, well-known services.
·         Port numbers 1024 through 49151 are the registered ports
·         Ports 49152 through 65535 are dynamic ports that are not officially used for any specific service, and can be used for any purpose. They are also used as ephemeral ports , from which software running on the host may randomly choose a port in order to define itself.[2] In effect, they are used as temporary ports primarily by clients when communicating with servers.

UDP Server:

import java.net.*;
import java.io.*;
public class UDPServer  {
    public static void main(String args[])  {
                        DatagramSocket aSocket = null;
                        try  {
                                    aSocket = new DatagramSocket(8117);
                                                           
                                    byte[] buffer = new byte[1000];
                                    while(true)
                                    {
                                                DatagramPacket request = new DatagramPacket(buffer, buffer.length);
                                                aSocket.receive(request);    
                                                DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(),
                                                request.getAddress(), request.getPort());
                                                aSocket.send(reply);
                                    }
                        }
                        catch (SocketException e)
                        {
                                    System.out.println("Socket: " + e.getMessage());
                        }
                        catch (IOException e)
                        {         
                                    System.out.println("IO: " + e.getMessage());
                        }
                        finally
                        {
                                    if(aSocket != null) aSocket.close();
                        }
            }
}

UDP Client:

import java.net.*;
import java.io.*;
public class UDPClient  {
   public static void main(String args[])  {
      DatagramSocket aSocket=null;
      try  {
            aSocket=new DatagramSocket();
            byte[]m=args[0].getBytes();
            InetAddress aHost=InetAddress.getByName(args[1]);
            int serverPort=8117;
            DatagramPacket request=new            DatagramPacket(m,args[0].length(),aHost,serverPort);
            aSocket.send(request);
            byte[] buffer=new byte[1000];
            DatagramPacket reply=new DatagramPacket(buffer,buffer.length);
            aSocket.receive(reply);
            System.out.println("Reply:"+new String(reply.getData()));
      }
      catch(SocketException e)
      {   System.out.println("Socket:"+e.getMessage());  }
      catch(IOException e)
      {   System.out.println("IO:"+e.getMessage());   }
      finally
      {
            if(aSocket!=null)
               aSocket.close();
      }
   }
}

UDP: OUTPUT
C:\Documents and Settings\cse4y>e:
E:\>cd Lab
E:\Lab>cd UDP
E:\Lab\UDP>javac *.java
E:\Lab\UDP>java UDPServer 127.0.0.1
C:\Documents and Settings\cse4y>e:
E:\>cd Lab
E:\Lab>cd UDP    
E:\Lab\UDP>java UDPClient hello 127.0.0.1  
Reply:hello

Bulletin Board Implementation Using JSP

Bulletin Board Implementation Using JSP

Start.jsp:
          <h2>Bulliten Board</h2>
<form method="post" action="bb.jsp" >
Select Group : <select name="grp">
                        <option value="grp1"/>Group-1
                         <option value="grp2"/>Group-2
                         </select><br><br>
UserName : <input type="text" name="usr" /><br><br>
Password : <input type="password" name="pass" /><br><br>
                <input type="button" value="Log In" onclick="submit()"/>
 </form>

bb.jsp:
<%@ page import="java.sql.*" %>
<%
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String grp=request.getParameter("grp");
String usr=request.getParameter("usr");
String pass=request.getParameter("pass");

try
{
Connection con =DriverManager.getConnection("jdbc:odbc:server","scott","tiger");
PreparedStatement stmt=con.prepareStatement("select * from login where usr='"+usr+"' and pass='"+pass+"' and grp='"+grp+"'");
ResultSet rs=stmt.executeQuery();
if(rs.next())
            {          %>
<form method="post" action="inbox.jsp" >
<input type="hidden" name="flag" value="<%=grp%>"/>
<input type="button" value="Go to INBOX - - >" onclick="submit()"/>
            </form>
           
<%}
else
            {
%>
Login failed<br>
<form method="post" action="start.jsp" >
            <input type="button" value="< - - Go Back" onclick="submit()"/>
            </form>
            <%
            }
             stmt.close();
}
catch(SQLException se)
{
            %>
Login failed<br>
<form method="post" action="start.jsp" >
            <input type="button" value="< - - Go Back" onclick="submit()"/>
            </form>
            <%
}         
%>

Inbox.jsp:
<%
String flag=request.getParameter("flag");
%>
<h2>INBOX</h2>
<form method="post" action="read.jsp" target="_blank">
<input type="hidden" name="flag" value="<%=flag%>"/>
<input type="button" value="Read Messages" onclick="submit()"/>
</form><br>
<form method="post" action="write.jsp" target="_blank">
<input type="hidden" name="flag" value="<%=flag%>"/>
<input type="button" value="Write Message" onclick="submit()"/>
</form><br>
<form method="post" action="start.jsp" >
<input type="hidden" name="flag" value="<%=flag%>"/>
           <input type="button" value="LogOut" onclick="submit()"/>
           </form>
Read.jsp:
<%@ page import="java.sql.*" %>
<%
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String flag=request.getParameter("flag");

try
{
Connection con =DriverManager.getConnection("jdbc:odbc:server","scott","tiger");
PreparedStatement stmt=con.prepareStatement("select * from "+flag+"");
ResultSet rs=stmt.executeQuery();
%><h3>Messages</h3><br><%
while(rs.next())
            {
     out.println(rs.getString(1)+"<br>");
                        }
            %>
<br><form method="post" action="inbox.jsp" >
<input type="hidden" name="flag" value="<%=flag%>"/>
<input type="button" value="< - - Go back to INBOX" onclick="submit()"/>
            </form>
           
<%
             stmt.close();
}
catch(SQLException se)
{
            %>
Database ERROR
            <%
}         
%>
Write.jsp:
<%
String flag=request.getParameter("flag");
%>
<form method="post" action="update.jsp" >
<input type="hidden" name="flag" value="<%=flag%>"/>
Enter message here : <input type="text" name="msg"/><br>
<input type="button" value="Write message to Database" onclick="submit()"/>
</form>

Update.jsp:
<%@ page import="java.sql.*" %>
<%
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String flag=request.getParameter("flag");
String msg=request.getParameter("msg");
try
{
Connection con =DriverManager.getConnection("jdbc:odbc:server","scott","tiger");
PreparedStatement stmt=con.prepareStatement("insert into "+flag+" values('"+msg+"')");
int rs=stmt.executeUpdate();
if(rs  == 1)
 out.pintln("written successfully");
%>

<br><form method="post" action="inbox.jsp" >
<input type="hidden" name="flag" value="<%=flag%>"/>
<input type="button" value="< - - Go back to INBOX" onclick="submit()"/>
            </form>
           
<%
             stmt.close();
}
catch(SQLException se)
{
            %>
Database ERROR
            <%
}         
%>






Tables required –
1.      Login (grp varchar2(20), usr varchar2(20), pass varchar2(20));
2.      grp1 (msg varchar2(50));
3.      grp2 (msg varchar2(50));