Solved

Client server communication thru TCP/IP connection

Posted on 2002-04-09
4
196 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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
difference of if loops 23 68
Glassfish admin console not working 1 55
import as existing maven project 3 34
learn programming 8 66
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

685 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