Solved

Client server communication thru TCP/IP connection

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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
mapBully challenge 6 89
topping1 challenge 7 53
recursion example 16 70
Where to store the queries for modification of table 4 27
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

759 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