Второй поток завершается, а не зацикливается

1

Эта программа использует клиента для отправки объекта Computer (атрибут бренда, цены, количества), и сервер возвращает весь платеж обратно клиенту. Он должен иметь возможность непрерывно запускать цикл, который отправляет прямые потоки на сервер.

Однако после завершения второго потока программа останавливается. Мне нужно выяснить, как это сделать, спасибо. К классам относятся Computer, ComputerServer w/HandleAClient и ComputerClient. Я прошу прощения за редактирование, я все еще изучаю, как это использовать.

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


    }
}
  • 0
    Почему у вас есть 4 объекта сканера на System.in?
  • 0
    у меня были пропущенные строки, я решил это, выполнив scanner.nextLine () в конце цикла while. Спасибо
Теги:
multithreading
loops

1 ответ

0
Лучший ответ

Вы перепутались на сервере:

  1. Вы получаете объект в основном потоке, чем новый поток, который ничего не делает. Таким образом, вы получаете информацию из сокета только один раз.
  2. Другое соединение было получено без проблем, но старая информация о соединении была потеряна. Клиент писал в свой сокет, но вы ничего не сделали с ним, потому что вы потеряли ссылку на поток. Я полагаю, вы считали, что новый объект приходит на сервер как новый сокет, что было неправильно.

попробуйте использовать этот код для сервера:

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню