I've made a button which calls connect(); and then (new Thread(new client())).start();
What I want my class client to do is to keep sending the variable "iterationCounter" to the server class constantly trough the run method. the variable iterationCounter is changing value which then is printed out by the server. With help from the comments the client side now works.
public class client implements Runnable
{
public static int iterationCounter = 0;
private PrintStream p;
public static void serverConnect(int globalCount) throws UnknownHostException, IOException
{
iterationCounter = globalCount;
}
public void connect() throws UnknownHostException, IOException
{
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1",1342);
p = new PrintStream(s.getOutputStream());
//p.println(iterationCounter);
}
@Override
public void run() {
while(true)
{
if (p != null) // Make sure that p has been initialized
p.println(iterationCounter); // p will be resolved now
//System.out.println("Iteration: "+ iterationCounter); // WORKS, keeps printing out in the client window.
}
}
The problem I am getting right now is on the server side.
public class MainServer {
public static void main(String args[]) throws IOException
{
int iterations;
ServerSocket s1 = new ServerSocket(1342);
Socket ss = s1.accept();
Scanner sc = new Scanner(ss.getInputStream());
//iterations = sc.nextInt();
while(true)
{
iterations = sc.nextInt();
System.out.println("Server counted: " + iterations + " Iterations");
}
}
}
the error I get now is from the server side, line 40 is iterations = sc.nextInt();
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at TheServer.MainServer.main(MainServer.java:40)
答案 0 :(得分:1)
p cannot be resolved because it is declared as a variable inside connect(). You should declare it as a class variable, just make sure that the connect() method is called before run(), so p has a value assigned and is not null:
public class client implements Runnable
{
public static int iterationCounter = 0;
private PrintStream p;
public static void serverConnect(int globalCount) throws UnknownHostException, IOException
{
iterationCounter = globalCount;
}
public void connect() throws UnknownHostException, IOException
{
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1",1342);
p = new PrintStream(s.getOutputStream());
//p.println(iterationCounter);
}
@Override
public void run() {
while(true)
{
if (p != null) // Make sure that p has been initialized
p.println(iterationCounter); // p will be resolved now
//System.out.println("Iteration: "+ iterationCounter); // WORKS, keeps printing out in the client window.
}
}