Solved

where to put main method in simple server

Posted on 2003-11-25
8
233 Views
Last Modified: 2010-03-31
Hi, im trying to write a simple server that waits for connections and when it makes a connection it executes commands on a seperate thread for each connection. Below is the code i am using, I think its ok (it compiles, when it runs it just does nothing) and i know i have to use a main method (which is not there) but i cant see where i need it, any help at all is great
Cheers

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

public class serverz extends Frame implements Runnable{
     TextArea display;

     public serverz(){
          super("serverz");
          display = new TextArea(20 , 5);
          add("Center" , display);
          resize(300 , 150);
          show();
     }

   
      public void run(){
            serverz s = new serverz();
     s.runserverz();
      }
      
     public void runserverz(){

      ServerSocket serve = null;
     Socket connection;
     OutputStream output = null;

     BufferedReader input = null;


         try{
      
          serve = new ServerSocket(5003 , 1000);
          while(true){
          connection = serve.accept();
          display.setText("\nConnection received");
          output = connection.getOutputStream();
          String s = new String("Has connected\n");

          for(int i = 0; i < s.length(); ++i)
               output.write((int) s.charAt(i));

          display.appendText(
               "\nSent message");

          //receiving message from client
          input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          String buffer = null;
          while((buffer = input.readLine()) != null)
            display.appendText("\n" + buffer);
}
  }   //end while
     catch(IOException e){
          e.printStackTrace();
     }

}//end while


//} //end main

}
0
Comment
Question by:irish_paddy
  • 5
  • 3
8 Comments
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
import java.awt.* ;
import java.awt.event.* ;
import java.net.* ;
import java.io.* ;
import javax.swing.* ;

public class Serverz extends Frame
{
  TextArea display ;

  public Serverz()
  {
    super( "serverz" ) ;
    display = new TextArea( 20, 5 ) ;
    add( "Center", display ) ;
    resize( 300, 150 ) ;
    show() ;
  }

  public void runserverz()
  {

    ServerSocket serve = null ;
    Socket connection ;
    OutputStream output = null ;

    BufferedReader input = null ;

    try
    {

      serve = new ServerSocket( 5003, 1000 ) ;
      while( true )
      {
        connection = serve.accept() ;
        display.setText( "\nConnection received" ) ;
        output = connection.getOutputStream() ;
        String s = new String( "Has connected\n" ) ;

        for( int i = 0 ; i < s.length() ; ++i )
          output.write( ( int )s.charAt( i ) ) ;

        display.appendText(
            "\nSent message" ) ;

        //receiving message from client
        input = new BufferedReader( new InputStreamReader( connection.
            getInputStream() ) ) ;
        String buffer = null ;
        while( ( buffer = input.readLine() ) != null )
          display.appendText( "\n" + buffer ) ;
      }
    } //end while
    catch( IOException e )
    {
      e.printStackTrace() ;
    }

  } //end while

//} //end main

  public static void main( String[] args )
  {
    Serverz main = new Serverz() ;
    main.runserverz();
  }
}
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
I changed your classname to have a capital "S" too, as it makes it much easier for seeing what is a class, and what is a method...

You also didn't need Runnable
0
 
LVL 35

Accepted Solution

by:
TimYates earned 50 total points
Comment Utility
This lets you close the frame too, to close the app, and close the serversocket:

--------------------

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

public class Serverz extends Frame implements WindowListener
{
  TextArea display ;

  public Serverz()
  {
    super( "serverz" ) ;
    display = new TextArea( 20, 5 ) ;
    add( "Center", display ) ;
    resize( 300, 150 ) ;
    show() ;
    addWindowListener( this );
  }

  public void runserverz()
  {
    ServerSocket serve = null ;
    Socket connection ;
    OutputStream output = null ;

    BufferedReader input = null ;

    try
    {

      serve = new ServerSocket( 5003, 1000 ) ;
      while( true )
      {
        connection = serve.accept() ;
        display.setText( "\nConnection received" ) ;
        output = connection.getOutputStream() ;
        String s = new String( "Has connected\n" ) ;

        for( int i = 0 ; i < s.length() ; ++i )
          output.write( ( int )s.charAt( i ) ) ;

        display.appendText(
            "\nSent message" ) ;

        //receiving message from client
        input = new BufferedReader( new InputStreamReader( connection.
            getInputStream() ) ) ;
        String buffer = null ;
        while( ( buffer = input.readLine() ) != null )
          display.appendText( "\n" + buffer ) ;
      }
    } //end while
    catch( IOException e )
    {
      e.printStackTrace() ;
    }

  } //end runserverz

  // These operations are specified by the WindowListener interface so
  //  we must include them. However, they don't do anything in this
  //  do-nothing program
  public void windowClosed( WindowEvent e ){}
  public void windowOpened( WindowEvent e ){}
  public void windowDeiconified( WindowEvent e ){}
  public void windowIconified( WindowEvent e ){}
  public void windowDeactivated( WindowEvent e ){}
  public void windowActivated( WindowEvent e ){}

  /*
   windowClosing
   This operation is called in response to a windowClosing event. It should
   simply exit the program
   */
  public void windowClosing( WindowEvent e )
  {
    System.exit( 0 ) ;
  }

  public static void main( String[] args )
  {
    Serverz main = new Serverz() ;
    main.runserverz();
  }
}
0
 

Author Comment

by:irish_paddy
Comment Utility
Cheers for that. I want to start a seperate thread each time a client connects to the server, thats why i am implementing runnable
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 35

Expert Comment

by:TimYates
Comment Utility
http://www.acm.org/crossroads/xrds6-1/ovp61.html

shows how this can be achieved :-)

create a seperate runnable class that handles the socets when a connection is recieved :-)

Tim
0
 

Author Comment

by:irish_paddy
Comment Utility
I went to that site and it implements the thread on the client side, could you elaborate on how to apply threads to my program
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
Why did I get a C grade?

Just wondering...

> it implements the thread on the client side

No, it creates a seperate thread for each client that connects...  

The threads are created on the server side...sorry I didn't answer sooner...I was at the pub...

Sorry I didn't help you solve your problems....just wondering if you can explain the grade... after all, C is;

-----------

C: Because Experts' reliability are often judged by their grading records, many Experts would like the opportunity to clarify if you have questions about their solutions. If you have given the Expert(s) ample time to respond to your clarification posts and you have responded to each of their posts providing requested information; or if the answers, after clarification, lack finality or do not completely address the issue presented, then a "C" grade is an option. You also have the option here of just asking Community Support to delete the question.

-----------

from: http://www.experts-exchange.com/help.jsp#hi68
0
 

Author Comment

by:irish_paddy
Comment Utility
Fair enough, I didnt know that was what c was, c is still a fairly good answer in my view.  I never read that definition of the c grade. I should have given more time, my fault, wont happen again. Thx for your help, it did help me eventually solve the problem
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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…
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 …
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…

762 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

13 Experts available now in Live!

Get 1:1 Help Now