gpt4 book ai didi

java - 通过线程将变量从客户端发送到服务器

转载 作者:行者123 更新时间:2023-12-02 10:26:07 25 4
gpt4 key购买 nike

我制作了一个调用 connect() 的按钮;然后 (new Thread(new client())).start();

我希望我的类客户端做的是通过 run 方法不断将变量“iterationCounter”发送到服务器类。变量 iterationCounter 正在改变值,然后由服务器打印出来。在评论的帮助下,客户端现在可以工作了。

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.
}
}

我现在遇到的问题是在服务器端。

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");
}
}
}

我现在得到的错误来自服务器端,第 40 行是 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)

最佳答案

p 无法解析,因为它在 connect() 中被声明为变量。您应该将其声明为类变量,只需确保在 run() 之前调用 connect() 方法,这样 p 就会被赋值且不为 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.
}
}

关于java - 通过线程将变量从客户端发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53945489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com