Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Client server communication thru TCP/IP connection

Posted on 2002-04-09
4
Medium Priority
?
200 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

Industry Leaders: 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

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…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

610 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