简体   繁体   English

第二个线程退出而不是向前循环

[英]Second thread quits instead of looping forward

This program uses a client to send a Computer object (attributes brand, price, quantity) and the server returns the total charge back to the client. 该程序使用客户端发送Computer对象(属性,品牌,价格,数量),然后服务器将总费用返回给客户端。 It must be able to continuously run a loop that sends forward threads to a server. 它必须能够连续运行将正向线程发送到服务器的循环。

However, after the second thread should be completed, the program stops. 但是,应该完成第二个线程后,程序停止。 I need to figure out how to keep it running, Thank you. 我需要弄清楚如何使其继续运行,谢谢。 Classes attached are Computer , ComputerServer w/ HandleAClient , and ComputerClient . 附类是ComputerComputerServer W / HandleAClientComputerClient I apologize for the editing, i am still learning how to use this. 抱歉,我仍在学习如何使用此功能。

import java.io.Serializable;

public class Computer implements Serializable 
{
    private String brand;
    private double price;
    private int quantity;

    public Computer()
    {
        setBrand("");
        setPrice(0.0);
        setQuantity(0);
    }

    public Computer(String b, double p, int q)
    {
        setBrand(b);
        setPrice(p);
        setQuantity(q);
    }

    public String getBrand()
    {
        return brand;
    }

    public double getPrice()
    {
        return price;
    }

    public int getQuantity()
    {
        return quantity;
    }

    public void setBrand(String b)
    {
        brand = b;
    }

    public void setPrice(double p)
    {
        price = p;
    }

    public void setQuantity(int q)
    {
        quantity = q;
    }

    public String toString()
    {
        return("Brand: "+brand+"\t"+"Price: "+price+"\t"+"Quantity: "+quantity);
    }
}


import java.util.*;
import java.io.*;
import java.net.*;

public class ComputerClient
{
    public static void main(String args[])
    {
        Socket connection;

        Scanner scanner = new Scanner(System.in);

        Scanner quantity = new Scanner(System.in);
        Scanner price = new Scanner(System.in);
        Scanner brand = new Scanner(System.in);

        ObjectOutputStream output;
        ObjectInputStream input;

        String b;
        double p;
        int q;

        Object obj;

        try
        {
            int exit= 1;

            connection = new Socket("localhost",8000);

            output = new ObjectOutputStream(connection.getOutputStream());
            input = new ObjectInputStream(connection.getInputStream());

            while(exit!=-1)
            {

                System.out.println("Please Enter a Computer Brand\n");
                b = brand.nextLine();

                System.out.println("Please Enter the Price\n");
                p = price.nextDouble();

                System.out.println("Please Enter the Quantity\n");
                q = quantity.nextInt();


                Computer c = new Computer(b,p,q);


                output.writeObject(c);

                output.flush();


            //read back:

                obj=(Object)input.readObject();


                System.out.println(obj.toString());

                System.out.println("Press any Integer to Continue, To Exit Press -1");
                exit = scanner.nextInt();


            }
        }
        catch(ClassNotFoundException cnfe)
        {
            cnfe.printStackTrace();
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
}


import java.io.*;
import java.util.*;
import java.net.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

public class ComputerServer 
{
    public static void main(String args[])
    {
        ServerSocket serverSocket;
        Socket connection;

        ObjectInputStream input;
        ObjectOutputStream output;

        Computer c = null;

        Object obj;

        double totalCharge;

        try
        {
            serverSocket = new ServerSocket(8000);
            System.out.println("Waiting for Client");

            int clientNo = 1;

            ExecutorService threadExecutor = Executors.newCachedThreadPool();

            while(true)//runs indefinitely
            {
                connection = serverSocket.accept();

                input = new ObjectInputStream(connection.getInputStream());
                output = new ObjectOutputStream(connection.getOutputStream());

                obj = input.readObject();

                System.out.println("\nObject Received from Client:\n"+obj);

                if(obj instanceof Computer)
                {
                    totalCharge = ((Computer)obj).getPrice()*((Computer)obj).getQuantity();

                    HandleAClient thread = new HandleAClient(connection, clientNo, totalCharge);

                    threadExecutor.execute(thread);

                    output.writeObject(totalCharge);
                    output.flush();
                }


                clientNo++;
            }

        }
        catch(ClassNotFoundException cnfe)
        {
            cnfe.printStackTrace();
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }

    }//end of main
}

class HandleAClient implements Runnable
{
    //**SHOULD i do object...
    //Scanner input;
    //Formatter output;
    Object obj;

    ObjectOutputStream output;
    ObjectInputStream input;

    Socket connection;
    ServerSocket serverSocket;

    int clientNo;

    //variables for calculation
    //variables for calculation
    double price;
    double totalCharge;


    public HandleAClient(Socket connection, int clientNo, double totalCharge)
    {
        this.connection = connection;
        this.clientNo = clientNo;
        this.totalCharge = totalCharge;
    }

    public void run()
    {
        //ArrayList<Computer> cList = new ArrayList<Computer>();




            //connection = serverSocket.accept();




            /*while(input.hasNext())
            {
                //variable = input.next....
                //print out calculation
                price = input.nextDouble();
                System.out.println("Price received from client:\t"+clientNo+"is"+price);

                //DO CALCULATION, STORE IT

                for(Computer c: cList)//**TRYING a for loop
                {
                    totalCharge = ((Computer)c).getPrice() * ((Computer)c).getQuantity();

                    output.format("%.2f\n", totalCharge);

                    //output.flush();
                }
            //}*/

            System.out.println("\nTotal Charge\t"+totalCharge);
            System.out.println("\nThread"+"\t"+clientNo+"\t"+"ended");


    }
}

You messed up in a Server: 您搞砸了服务器:

  1. You are receiving object in a main thread, than you make a new thread that does nothing. 您在主线程中接收对象,而不是创建一个不执行任何操作的新线程。 So you receive information from the socket only once. 因此,您只能从套接字接收一次信息。
  2. Another connection was obtained without a problem, but the old connection information was lost. 顺利获得了另一个连接,但是旧的连接信息丢失了。 The client was writing to its socket but you didn't do anything with it, because you've lost a reference to the stream. 客户端正在向其套接字写入数据,但是您没有对其进行任何操作,因为您丢失了对该流的引用。 I suppose you thought that new object comes to the server as a new socket, which was wrong. 我想您以为是新对象作为新套接字进入服务器的,这是错误的。

try using this code for a Server: 尝试对服务器使用以下代码:

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class ComputerServer
{
    public static void main(String args[]) throws IOException
    {
        ServerSocket serverSocket;
        Socket connection;

        serverSocket = new ServerSocket(8000);
        int clientNo = 1;
        ExecutorService threadExecutor = Executors.newCachedThreadPool();
        while (true)// runs indefinitely
        {
            System.out.println("Waiting for client");
            connection = serverSocket.accept();
            System.out.println("Client connected: " + connection.getPort());
            HandleAClient thread = new HandleAClient(connection, clientNo);
            threadExecutor.execute(thread);
            clientNo++;
        }
    }
}

class HandleAClient implements Runnable
{
    ObjectOutputStream output;
    ObjectInputStream input;
    ServerSocket serverSocket;

    int clientNo;

    public HandleAClient(Socket connection, int clientNo)
    {
        this.clientNo = clientNo;
        try
        {
            this.input = new ObjectInputStream(connection.getInputStream());
            this.output = new ObjectOutputStream(connection.getOutputStream());
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void run()
    {
        while (true)
        {
            try
            {
                Object obj = input.readObject();

                System.out.println("\nObject Received from Client:\n" + obj);

                if (obj instanceof Computer)
                {
                    Computer c = (Computer) obj;
                    double totalCharge = c.price * c.quantity;
                    System.out.format("\nTotal Charge[%d]\t%f", clientNo,
                            totalCharge);
                    output.writeObject(totalCharge);
                    output.flush();
                }
            } catch (Exception e) { //JUST FOR BREVITY
                e.printStackTrace();
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM