Printstream in java

Hi,

i have java server and flash client. what i need is,

whenever i send data from flash server should printstream that data back to the client. So that i can display it in flash. Any help would be appreciated.

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class MultiThreadServer implements Runnable {
  Socket csocket;

  MultiThreadServer(Socket csocket) {
    this.csocket = csocket;
  }

  public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    System.out.println("Listening");
    while (true) {
      Socket sock = ssock.accept();
      System.out.println("Connected");
	BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            PrintStream ps = new PrintStream(
                    sock.getOutputStream());
            ps.println(br.readLine());

		if(br.readLine()==("data"))
      new Thread(new MultiThreadServer(sock)).start();
    }
  }

  public void run() {
    try {
      	System.out.println("hello");
		PrintStream pstream = new PrintStream(csocket.getOutputStream());
	while(true) {
              try{
		pstream.println("dead&dead1" + "\\u0000");
	  Thread.sleep(1000);
	  } catch (InterruptedException e) {
		e.printStackTrace();
  }	

}

      //for (int i = 100; i >= 0; i--) {
      //  pstream.println(i + " bottles of beer on the wall");
      //}
      //pstream.close();
      //csocket.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}

Thanks

AND… what’s the problem exactly?

Also, you might consider using the [ code ] tag to help format your code, so that those of us that might try to help, can read your code better. :slight_smile:


while (true) {
      Socket sock = ssock.accept();
      System.out.println("Connected");
      BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      str = br.readLine();
      //multi();
      PrintStream pstream = new PrintStream(csocket.getOutputStream());


i am getting the error “MultiThreadServer.java:27: non-static variable csocket cannot be referenced from
a static context
PrintStream pstream = new PrintStream(csocket.getOutputStream())”;

Are you getting your error during compile time or runtime?

If it happens during runtime could you please post a way to access the socket that you’re opening?

BTW, I’m not seeing any compile errors with the following code:


import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class MultiThreadServer implements Runnable {
	Socket csocket;
	
	MultiThreadServer(Socket csocket) {
		this.csocket = csocket;
	}
	
	public static void main(String args[]) throws Exception {
		ServerSocket ssock = new ServerSocket(1234);
		System.out.println("Listening");
		while (true) {
			Socket sock = ssock.accept();
			System.out.println("Connected");
			BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
			PrintStream ps = new PrintStream(
					sock.getOutputStream());
			ps.println(br.readLine());
			
			if(br.readLine()==("data"))
				new Thread(new MultiThreadServer(sock)).start();
		}
	}
	
	public void run() {
		try {
			System.out.println("hello");
			PrintStream pstream = new PrintStream(csocket.getOutputStream());
			while(true) {
				try{
					pstream.println("dead&dead1" + "\\u0000");
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
			
			//for (int i = 100; i >= 0; i--) {
			// pstream.println(i + " bottles of beer on the wall");
			//}
			//pstream.close();
			//csocket.close();
		} catch (IOException e) {
			System.out.println(e);
		}
	}
}

please change while loop printstream statement to,

while (true) {
Socket sock = ssock.accept();
System.out.println(“Connected”);
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
str = br.readLine();
//multi();
PrintStream pstream = new PrintStream(csocket.getOutputStream());
ps.print(str);
}

I am getting compile time error,
MultiThreadServer.java:29: non-static variable csocket cannot be referenced from
a static context
PrintStream pstream = new PrintStream(csocket.getOutputStream());

The compiler error is correct.

You may not make a static reference to an instance variable.

The public static void main method is considered a static reference. There can only be one instance of that method for any application. Your Socket csocket is an instance variable meaning that there will be one variable per instance of your MultiThreadServer class. Therefore the static reference (your main method), which there is only ever one of, would never know which individual instance of csocket to work with.

There are a few different things you could try. Make your Socket scocket instance static.

Or, you could create a new method perhaps called init() that is called by your classes constructor and place the code you have in your main method there.

Or, there could be other solutions.

<minor point>
For general programming practices and technique you should consider making your Socket scocket variable private.
</minor point>

thanks,

wrote a separate method,

getting error,

MultiThreadServer.java:19: ‘;’ expected
ret = PrintStream ps = new PrintStream(output);

public String init(String output)
{
String ret;
String ps;
try
{
ret = PrintStream ps = new PrintStream(output);

    return ret;
 }
catch(IOException e)
{
    System.out.print(e);
}

}

also tried,

public class MultiThreadServer implements Runnable {
public static Socket csocket;

i am getting the error,

MultiThreadServer.java:11: cannot find symbol
symbol : variable csocket
location: class MultiThreadServer
this.csocket = csocket;


public String init(String output) {
  String ret;
  String ps;
  try {
    ret = PrintStream ps = new PrintStream(output); [COLOR="Red"]//*[/COLOR]

    return ret;
  } catch(IOException e) {
    System.out.print(e);
  }
}

* What are you trying to accomplish here?

A: ret = PrintStream ps - you can’t assign a PrintStream to a String
B: ret = PrintStream ps - you already declared ps as a String
C: Shouldn’t your return value be a PrintStream?
C2: return new PrintStream( output ); is the entirety of code you need in this method (other than the try/catch, of course)

This might be in different topic but… why are you creating your own Java server? This is 100% fit for any JSP server like tomcat. Multithreading is already handled “very” well in this. I would make a RESTful service that’s run on tomcat. Just a thought.

If you’re “truly” hardcore and likes to waste time then you can use JDK 1.6’s HTTP embedded server. I created web service provider using that for fun but not for production!

http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/package-summary.html

Still the static vs instance variable issue.

The ‘this’ modifier refers to ‘this instance’, which implies that you’re dealing with an instance of a class. Since you changed your Socket csocket attribute to be static, it can no longer be referenced in a non-static way.

if your remove the ‘this.’ from in front of your csocket it should work. BUT, you might need to change your method/constructor level variables name so that you won’t get a compiler error for that. (The compiler will not understand which csocket is the static one and which one is the method/constructor variable.) You might try accessing your static csocket the following way ‘MultiThreadServer.csocket’.

I think this is a school assignment.

When you receive the “non-static variable X cannot be referenced from
a static context” error, you have attempted to use a non-static variable in a static method.

Background:

A method that is defined as static ‘exists’ without the need to create an instance of the class.

A non-static variable (aka: member variable) does not exist until an instance has been created.

So when you write:


public static void main( String[] args ) {
  PrintStream pstream = new PrintStream(csocket.getOutputStream());
}

What Java actually sees is:


public static void main( String[] args ) {
  PrintStream pstream = new PrintStream(hellIfIKnowItDoesn'tExist.getOutputStream());
}

The best way to solve this is to create an instance of your class to work with:


public static void main( String[] args ) {
  new MyClass(); //if you just want to get it going, or
  MyClass myClass = new MyClass(); // if you want to control it from main
}
public MyClass() {
  PrintStream pstream = new PrintStream(csocket.getOutputStream());
}

Also, next time, start your own thread.

EDIT: Moderator note - “start your own thread” refers to a previous spam post that has been removed - Mittineague