Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / December 2005

Tip: Looking for answers? Try searching our database.

non-static method error message

Thread view: 
albertasandrulis@gmail.com - 02 Dec 2005 00:22 GMT
HI,
 I want to write a simple server/client chat program. But i get an
error message:

"server.java:49: non-static method accept() cannot be referenced from a
static context
         Socket clientSocket = ServerSocket.accept();"
                                           ^

I dont know much of a static, non-static methods yet, so I ask:  Could
some one fix this problem for me?

The code provided is not fully done yet, and after it is fixed more
errors can appiear too :-). All suggestions are wellcome.

The code:
================================================================
import java.lang.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;

class Server extends JFrame{
  JFrame mainFrame = null;
  JTextArea text = new JTextArea();
  JTextField line = new JTextField();
  JButton button = new JButton("Ijungti");
  JLabel label = new JLabel("");
  turnOn init;

 Server() {
   init = new turnOn();
   setSize(300, 200);
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   Container kont = getContentPane();
   kont.setLayout(null);
    kont.add(text);
    kont.add(line);
    kont.add(button);
    kont.add(label);
    text.setLineWrap(true);
    text.setEditable(false);
    text.setBounds(150, 0, 140, 150);
    line.setBounds(150, 155, 140, 18);
    button.setBounds(25, 100, 100, 25);
    label.setBounds(25, 50, 100, 25);
 }

 class turnOn {
   ServerSocket serverSocket;
   turnOn() {
     try {
       serverSocket = new ServerSocket(12111);
     }
     catch(IOException ioe) {
       label.setText("error..");
       System.exit(-1);
     }
     label.setText("On.");
     int id = 0;
     while(true) {
       try {
         Socket clientSocket = ServerSocket.accept();
         client cliThread = new client(clientSocket, id++);
         cliThread.start();
       }
       catch(IOException ioe) {
         label.setText("Exception encountered on accept. Ignoring.
Stack Trace :");
         ioe.printStackTrace();
       }
     }
   }
 }

 public class client extends Thread {
   Socket soket;
    int kl_id = -1;
    boolean run = true;
    client(Socket s, int id) {
     soket = s;
     kl_id = id;
    }
    public void run() {
     BufferedReader in = null;
     PrintWriter out = null;
     try {
       in = new BufferedReader(new
InputStreamReader(soket.getInputStream()));
       out = new PrintWriter(new
OutputStreamWriter(soket.getOutputStream()));
       while(run) {
         String klient = in.readLine();
         text.append(klient);
         if(klient.equalsIgnoreCase("quit")) {
           run = false;
            label.setText("end connection: " + kl_id);
         }
         else {
           out.println(klient);
           out.flush();
         }
       }
     }
     catch(Exception e) {
       e.printStackTrace();
     }
     finally {
       try {
         in.close();
         out.close();
         soket.close();
         label.setText("...Stopped");
        }
       catch(IOException ioe) {
         ioe.printStackTrace();
       }
     }
    }
 }

 public static void main(String[] arg) {
   new Server().setVisible(true);
 }
}

=================================================================
Roedy Green - 02 Dec 2005 01:39 GMT
>"server.java:49: non-static method accept() cannot be referenced from a
>static context
[quoted text clipped - 3 lines]
>I dont know much of a static, non-static methods yet, so I ask:  Could
>some one fix this problem for me?

accept is an instance method, not a static method. You need a
ServerSocket object.

ServerSocket serverSocket = new ServerSocket( port );

Then it calls accept, which blocks until a call comes in.

Socket clientSocket = serverSocket.accept();

see http://mindprod.com/jgloss/socket.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Vmz - 02 Dec 2005 03:58 GMT
>accept is an instance method, not a static method. You need a
>ServerSocket object.

> ServerSocket serverSocket = new ServerSocket( port );

>Then it calls accept, which blocks until a call comes in.

>Socket clientSocket = serverSocket.accept();
===========================================================
Dont i do it few lines before like shown in code:

     try {
       serverSocket = new ServerSocket(12111);
     }
     catch(IOException ioe) {
       label.setText("error..");
       System.exit(-1);
     }

Then goes my problem:

     while(true) {
       try {
         Socket clientSocket = ServerSocket.accept();
         client cliThread = new client(clientSocket, id++);
         cliThread.start();
       }
       catch(IOException ioe) {
         label.setText("Exception encountered on accept. Ignoring.
Stack Trace :");
         ioe.printStackTrace();
       }
     }

I tryed to modify as you said, but still getting same error.
Roedy Green - 02 Dec 2005 04:07 GMT
> Socket clientSocket = ServerSocket.accept();

ServerSocket is a class. serverSocket is a variable.

Look at my code carefully.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Monique Y. Mudama - 02 Dec 2005 19:08 GMT
>>accept is an instance method, not a static method. You need a
>>ServerSocket object.
[quoted text clipped - 31 lines]
>
> I tryed to modify as you said, but still getting same error.

And here's a great argument for naming your variables usefully.  If
you had named your ServerSocket variable almost anything else, the
problem would have been obvious.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Vmz - 03 Dec 2005 00:07 GMT
OK,
i have fixed the code, now it compiles with no errors. The problem is
when i try to run it, it starts and nothing happens, i dont see window
i'm supposed to see. Can any of you check the code, and try to compile
and run it. And explain what is the problem ?
code:
=============================================================
import java.lang.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;

class Server extends JFrame{
  JFrame mainFrame = null;
  JTextArea text = new JTextArea();
  JTextField line = new JTextField();
  JButton button = new JButton("Ijungti");
  JLabel label = new JLabel("");
  turnOn init;

 Server() {

   setSize(300, 200);
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   Container kont = getContentPane();
   kont.setLayout(null);
    kont.add(text);
    kont.add(line);
    kont.add(button);
    kont.add(label);
    text.setLineWrap(true);
    text.setEditable(false);
    text.setBounds(150, 0, 140, 150);
    line.setBounds(150, 155, 140, 18);
    button.setBounds(25, 100, 100, 25);
    label.setBounds(25, 50, 100, 25);
   init = new turnOn();
 }

 class turnOn {
   ServerSocket serverSocket;
   turnOn() {
     try {
       serverSocket = new ServerSocket(12111);
     }
     catch(IOException ioe) {
       label.setText("error..");
       System.exit(-1);
     }
     label.setText("On.");
     int id = 0;
     while(true) {
       try {
         Socket clientSocket = serverSocket.accept();
         client cliThread = new client(clientSocket, id++);
         cliThread.start();
       }
       catch(IOException ioe) {
         label.setText("Exception encountered on accept. Ignoring.
Stack Trace :");
         ioe.printStackTrace();
       }
     }
   }
 }

 public class client extends Thread {
   Socket soket;
    int kl_id = -1;
    boolean run = true;
    client(Socket s, int id) {
     soket = s;
     kl_id = id;
    }
    public void run() {
     BufferedReader in = null;
     PrintWriter out = null;
     try {
       in = new BufferedReader(new
InputStreamReader(soket.getInputStream()));
       out = new PrintWriter(new
OutputStreamWriter(soket.getOutputStream()));
       while(run) {
         String klient = in.readLine();
         text.append(klient);
         if(klient.equalsIgnoreCase("quit")) {
           run = false;
            label.setText("end connection: " + kl_id);
         }
         else {
           out.println(klient);
           out.flush();
         }
       }
     }
     catch(Exception e) {
       e.printStackTrace();
     }
     finally {
       try {
         in.close();
         out.close();
         soket.close();
         label.setText("...Stopped");
        }
       catch(IOException ioe) {
         ioe.printStackTrace();
       }
     }
    }
 }

 public static void main(String[] arg) {
   new Server().setVisible(true);
 }
}

========================================================
Andrew McDonagh - 03 Dec 2005 00:11 GMT
> OK,
> i have fixed the code, now it compiles with no errors. The problem is
[quoted text clipped - 12 lines]
>
> class Server extends JFrame{

here's a hint....

>    JFrame mainFrame = null;

>    JTextArea text = new JTextArea();
>    JTextField line = new JTextField();
>    JButton button = new JButton("Ijungti");
>    JLabel label = new JLabel("");
>    turnOn init;

snipped
Noodles Jefferson - 03 Dec 2005 00:26 GMT
> > OK,
> > i have fixed the code, now it compiles with no errors. The problem is
[quoted text clipped - 4 lines]
> > =============================================================
> > import java.lang.*;

You don't have to import java.lang.*;

It's already automatically imported into every program you write.

> > import java.util.*;
> > import java.io.*;
[quoted text clipped - 16 lines]
>
> snipped

Signature

Noodles Jefferson
mhm31x9 Smeeter#29 WSD#30
sTaRShInE_mOOnBeAm aT HoTmAil dOt CoM

"Our earth is degenerate in these latter days, bribery and corruption
are common, children no longer obey their parents and the end of the
world is evidently approaching."
--Assyrian clay tablet 2800 B.C.

IchBin - 03 Dec 2005 02:23 GMT
> OK,
> i have fixed the code, now it compiles with no errors. The problem is
[quoted text clipped - 10 lines]
> import javax.swing.*;
> import java.net.*;

This what you are actually using.. no big deal.

import java.awt.Container;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

Not sure why you have this. It is not used/referenced.

>    JFrame mainFrame = null;

>    JTextArea text = new JTextArea();
>    JTextField line = new JTextField();
[quoted text clipped - 18 lines]
>     button.setBounds(25, 100, 100, 25);
>     label.setBounds(25, 50, 100, 25);
Add this..
        this.setVisible(true);

>     init = new turnOn();
>   }

Signature

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA
http://weconsultants.servebeer.com/JHackerAppManager
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)

Thomas Hawtin - 03 Dec 2005 02:45 GMT
My style is to run through code, highlighting anything that pops out at
me (as not been written by myself). Don't take it personally...

> import java.lang.*;
> import java.util.*;
[quoted text clipped - 3 lines]
> import javax.swing.*;
> import java.net.*;

Is there anything you don't want? :) It generally makes things easier to
understand, test and debug if each (outer) class is in its own file and
has a definite field of responsibility.

> class Server extends JFrame{

It's also generally a bad idea to extend a class that you do not need to.

>    JFrame mainFrame = null;

Particularly when you do this. :) Although you don't appear to have used it.

>     text.setBounds(150, 0, 140, 150);
>     line.setBounds(150, 155, 140, 18);
>     button.setBounds(25, 100, 100, 25);
>     label.setBounds(25, 50, 100, 25);

Learn the layout managers, for they obsolete this kind of nonsense. Just
skip SpringLayout, that sucks.

>   class turnOn {

It's much easier to understand code if it all uses the same conventions.
Fortunately the Java conventions are well established.

>         label.setText("error..");
>         System.exit(-1);

That text is unlikely ever to see the light of day (unless you have a
SecurityManager set).

>      while(true) {
>         try {
>           Socket clientSocket = serverSocket.accept();

Is this going to stop this thread inappropriately? Given that we have
used Swing components, we should be on the AWT Event Dispatch Thread
(EDT), and therefore should return promptly. In your case, to return
promptly to main, where you setVisible on the frame. This appears to be
your problem.

>   public class client extends Thread {

Again, don't extend classes you do not need to. Implement Runnable and
pass that to a Thread constructor.

>         in = new BufferedReader(new
> InputStreamReader(soket.getInputStream()));
>         out = new PrintWriter(new
> OutputStreamWriter(soket.getOutputStream()));

You probably want to specify the character set for InputStreamReader and
OutputStreamWriter. The default is to pick up whatever the server
happens to be configured for at the time. UTF-8 or ISO-8859-1 are useful
choices (see java.nio.charset.CharSet class description).

As you are (attempting) to close the socket it wouldn't matter in this
case, but to be very picky if, say, the BufferedReader were to fail
construction (OutOfMemoryError, say) then you would not be able to close
the underlying stream. But parts of java.io get that wrong anyway.

>         while(run) {
>           String klient = in.readLine();

BufferedReader.readLine will return null when the socket stream is closed.

>      finally {
>        try {
>          in.close();
>          out.close();

Depending on the failure, these streams may not have been created yet.
Further, in situations like this, if closing the first stream fails, the
second one will not even be attempted.

>   public static void main(String[] arg) {
>     new Server().setVisible(true);
>   }

You need some outrageous boilerplate here (or somewhere) to run the
Swing code in the Event Dispatch Thread (EDT).

    public static void main(String[] arg) {
        java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Server().setVisible(true);
                }
        });
    }

It's probably worth googling for Swing threading articles. Although they
aren't all entirely accurate, they might be more helpful than me.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Roedy Green - 03 Dec 2005 03:58 GMT
>text.setBounds(150, 0, 140, 150);
>    line.setBounds(150, 155, 140, 18);
>    button.setBounds(25, 100, 100, 25);
>    label.setBounds(25, 50, 100, 25);

you are coding in C here. See http://mindprod.com/jgloss/layout.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.