?
Solved

Client server communication thru TCP/IP connection

Posted on 2002-04-09
4
Medium Priority
?
199 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 200 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
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 video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month8 days, 7 hours left to enroll

765 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