Solved

Client server communication thru TCP/IP connection

Posted on 2002-04-09
4
193 Views
Last Modified: 2010-03-31
Write a program to depict a client server communication using TCP/IP connection. Give appropriate messages while communicating i.e. whether client is getting connected or no, whether server is ready or no. On the client side the data should be taken in a JApplet having border layout. It should consist of textfield wherein the client enters the messages to be sent and a textarea wherein responses can be displayed from the server. The server should convert the message in upper case and send it back to the client.
0
Comment
Question by:pankajp
4 Comments
 
LVL 4

Expert Comment

by:pellep
ID: 6928006
homework?
0
 
LVL 92

Expert Comment

by:objects
ID: 6929572
So what's your problem?
0
 
LVL 3

Accepted Solution

by:
msterjev earned 50 total points
ID: 6930934
The server is:
import java.net.*;
import java.util.*;
import java.io.*;

public class HttpServer
{
      public static void main(String[] args)
      {
            ServerSocket ss=null;
            try
            {
                  ss=new ServerSocket(9090);
                  System.out.println(new Date().toGMTString()+"> Server started . . .");
                  while(true)
                  {
                        new HttpServerThread(ss.accept());
                        System.out.println(new Date().toGMTString()+"> client accepted!");
                  }
            }
            catch(Exception e)
            {
                  e.printStackTrace();
            }
      }
}

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

public class HttpServerThread extends Thread
{
      protected Socket socket;
      
      public HttpServerThread(Socket socket)
      {
            this.socket=socket;
            start();
      }
      
      public void run()
      {
            DataInputStream in=null;
            DataOutputStream out=null;
            String line="";
            String file;
            byte[] buffer=null;
            boolean success;
            try
            {
                  in=new DataInputStream(socket.getInputStream());
                  out=new DataOutputStream(socket.getOutputStream());
                  line=in.readLine();
                  if(line.startsWith("GET"))
                  {
                        //This is http request
                        StringTokenizer st=new StringTokenizer(line);
                        st.nextToken();
                        file=st.nextToken().trim().substring(1);
                        System.out.println(new Date().toGMTString()+"> looking for file: "+file);
                        success=false;
                        try
                        {
                              DataInputStream fin=new DataInputStream(new FileInputStream(file));
                              buffer=new byte[fin.available()];
                              fin.readFully(buffer);
                              fin.close();
                              success=true;
                        }
                        catch(Exception fe)
                        {
                              success=false;
                        }
                        if(success)
                        {
                              out.writeBytes("HTTP/1.0  200 OK\r\n");
                              out.writeBytes("Content-Length: "+buffer.length+"\r\n");
                              if(file.indexOf(".class")!=-1)
                                 out.writeBytes("Content-Type: application/java\r\n");
                              else
                                 out.writeBytes("Content-Type: text/html\r\n");
                              out.writeBytes("Connection: Close\r\n\r\n");
                              out.write(buffer);
                              out.flush();
                        }
                        else
                        {
                              out.writeBytes("HTTP 404 Not Found\r\n\r\n");
                              out.flush();
                        }
                        out.close();
                        in.close();
                        socket.close();
                  }
                  else
                  {
                        do
                        {
                              System.out.println(new Date().toGMTString()+"> Readed line: "+line);
                              out.writeBytes(line.toUpperCase()+"\r\n");
                              out.flush();
                        }
                        while((line=in.readLine())!=null);
                        in.close();
                        out.close();
                  }
            }
            catch(Exception e)
            {
                  try
                  {
                        if(socket!=null)
                              socket.close();
                  }
                  catch(Exception ignored){}
            }
      }
}

The Applet code is:

import javax.swing.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class Client extends JApplet implements ActionListener,Runnable
{
      JButton connect;
      JButton disconnect;
      JTextField toServer;
      JTextArea output;
      JPanel north;
      JPanel center;
      Thread listener;
      Socket socket;
      DataOutputStream out;
      DataInputStream in;
      
      public void init()
      {
            setSize(500,500);
            getContentPane().setLayout(new BorderLayout());
            connect=new JButton("Connect...");
            disconnect=new JButton("Disconnect");
            disconnect.setEnabled(false);
            toServer=new JTextField();
            output=new JTextArea();
            north=new JPanel(new GridLayout(2,2));
            center=new JPanel(new BorderLayout());
            north.add(connect);
            north.add(disconnect);
            north.add(new JLabel("To server:"));
            north.add(toServer);
            getContentPane().add(north,BorderLayout.NORTH);
            center.add(new JLabel("Output:"),BorderLayout.NORTH);
            center.add(new JScrollPane(output),BorderLayout.CENTER);
            getContentPane().add(center);
            connect.addActionListener(this);
            disconnect.addActionListener(this);
            toServer.addActionListener(this);
      }
      
      public void start(){}
      public void stop(){}
      
      public void actionPerformed(ActionEvent e)
      {
            if(e.getSource()==connect)
            {
                  try
                  {
                        socket=new Socket(getCodeBase().getHost(),getCodeBase().getPort());
                        in=new DataInputStream(socket.getInputStream());
                        out=new DataOutputStream(socket.getOutputStream());
                        connect.setEnabled(false);
                        disconnect.setEnabled(true);
                        output.setText("");
                        output.setText(new Date().toGMTString()+"> Client connected to the server...");
                        if(listener==null)
                        {
                              listener=new Thread(this);
                              listener.start();
                        }
                  }
                  catch(Exception ex)
                  {
                        in=null;
                        out=null;
                        ByteArrayOutputStream baos=new ByteArrayOutputStream(1024);
                        ex.printStackTrace(new PrintStream(baos));
                        output.setText(baos.toString());
                  }
            }
            if(e.getSource()==disconnect)
            {
                  if(listener!=null)
                  {
                        listener.stop();
                        listener=null;
                  }
                  try
                  {
                        if(socket!=null)
                              socket.close();
                  }
                  catch(Exception ex){}
                  connect.setEnabled(true);
                  disconnect.setEnabled(false);
                  output.setText("");
            }
            if(e.getSource()==toServer)
            {
                  
                  if(out!=null)
                  {
                        try
                        {
                              out.writeBytes(toServer.getText()+"\r\n");
                              out.flush();
                        }
                        catch(Exception ex){}
                  }
            }
      }
      
      public void run()
      {
            String line="";
            output.setText(output.getText()+"\n"+new Date().toGMTString()+"> Listening thread started...");
            while(true)
            {
                  try
                  {
                        line=in.readLine();
                        output.setText(output.getText()+"\n"+line);
                  }
                  catch(Exception e){}
            }
      }
}

The html page is:

<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<APPLET code="Client.class" codebase="." WIDTH=500 HEIGHT=500>
</APPLET>
</BODY>
</HTML>


Start the server with:

java HttpServer

Then start appletviewer with:

appletviewer http://localhost:9090/Demo.htm

P.S.
You should increase the points!
0
 

Author Comment

by:pankajp
ID: 6931336
I liked the answere as the code is appropriate, up to the mark & also easy to comprehend.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Android studio getdrawable(int) is deprecated 4 39
allswap challenge 6 77
PDFBox - convert image to PDF, PDF resolution 3 117
Java Options in Zimbra Server 2 46
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now