简体   繁体   中英

Transferring a DataOutputStream

I have a program that connects client threads to a cinema through a socket. the client transfers his details (client no., required tickets) the cinema processes the request in another thread that makes sure there is enough seats available. as you will see in the code, i have a slight problem with figuring out how to send a feedback to the client from the cinema(server), the code presented is not completed, i just wanted to give you an idea of how it looks. my idea is to transfer the dataOutputStream to the cinemaThread and when its done, the cinema thread will return the feedback through the stream to the client is it possible?

Client side

import java.util.Random;
/**
 * this class in designed to define client properties
 * @author David and Adam
 *
 */
public class Client extends Thread{

    private int serialNumber;
    private int NumberOfTickets;
    private String creditNumber;
    private String serverPort;
    private int rowNumber;

    /**
     * full constructor
     * @param serialNumber
     * @param NumberOfTickets
     * @param creditNumber
     */
    public Client(int serialNumber){
        this.serialNumber = serialNumber;
        this.NumberOfTickets = generateTicketNumber();
        this.creditNumber = generateCreditNumber();
        this.rowNumber = -1;
    }

    /**
     * returns a value in the required number of ticket range.
     * @return
     */
    private int generateTicketNumber(){
        return (new Random()).nextInt(Constants.MaxNumberOfTickets-1)+Constants.MinNumberOfTickets;
    }

    /**
     * returns a random credit number constructed of 16 digits.
     * @return
     */
    private String generateCreditNumber(){
        String s = String.valueOf((new Random()).nextInt(9)+1);
        for(int i=0 ; i<16 ; i++){
            s = (new Random()).nextInt()+s;
        }
        return s;
    }

Server side

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * an implementation of server side defined as cinema hall
 * @author David
 *
 */
public class Cinema {
    private int[][] cinemaHall;
    private int ticketPrice;
    private int securedPort;
    private int numberOfRequests;

    /**
     * full constructor
     * 
     */
    public Cinema(){
        this.numberOfRequests = 0;
        initializeCinemaHall();
        setTicketPrice();
        setSecuredPort();
    }


    /**
     * initializes cinema hall to 0's
     */
    private void initializeCinemaHall(){
        this.cinemaHall = new int[10][10];
        for(int i=0 ; i<cinemaHall.length ; i++)
            for(int j=0 ; j<cinemaHall.length ; j++)
                this.cinemaHall[i][j] = 0;
    }

    /**
     * generates the ticket price on sale
     */
    private void setTicketPrice(){
        this.ticketPrice = Constants.TicketSalePrice;
    }
    /**
     * sets the secured port 
     * 
     */
    private void setSecuredPort(){
        this.securedPort = Constants.SecuredPort;
    }
        public int[][] getCinemaHall() {
        return cinemaHall;
    }


    public void setCinemaHall(int[][] cinemaHall) {
        this.cinemaHall = cinemaHall;
    }


    public int getTicketPrice() {
        return ticketPrice;
    }


    public void setTicketPrice(int ticketPrice) {
        this.ticketPrice = ticketPrice;
    }


    public int getNumberOfRequests() {
        return numberOfRequests;
    }


    public void setNumberOfRequests(int numberOfRequests) {
        this.numberOfRequests = numberOfRequests;
    }


    /**
     * main function for establishing communication between cinema and customers
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException{
        Cinema cinema = new Cinema();

        ServerSocket server = new ServerSocket(Constants.ServerPort);
        System.out.println("**********Yes Planet server in listening**********");

        // create a connection to clients
        while(cinema.numberOfRequests<Constants.MaxClientNumber){
            try {

                //wait for client
                Socket s = server.accept();
                System.out.println("Client connected to socket");
                // get client info
                DataInputStream dis = new DataInputStream(s.getInputStream());

                String clientInfo = dis.readLine();
                String[] details = clientInfo.split("/");

                try {
                    // parse data to correct type and send data to cinema thread
                    Thread cinemaThread = new CinemaThread(cinema, Integer.parseInt(details[0])
                            , Integer.parseInt(details[1]), details[2]);
                    cinemaThread.start();
                }
                catch (Exception e){
                    System.out.println("An error has occured, client request have been canceled");
                }

            } catch (IOException e) {
                System.out.println("Connection error ");
                e.printStackTrace();
            }

        }
    }
}

Cinema Thread

public class CinemaThread extends Thread{
    private int clientNumber;
    private Cinema cinema;
    private int requiredTickets;
    private String clientCreditNumber;
    private boolean occupied;
    private int lineNumber;
    private boolean alive;
    /**
     * full constructor
     * @param clientNumber
     * @param cinema
     * @param requiredTickets
     * @param clientCreditNumber
     */
    public CinemaThread(Cinema cinema, int clientNumber, int requiredTickets, String clientCreditNumber){
        this.clientNumber = clientNumber;
        this.cinema = cinema;
        this.requiredTickets = requiredTickets;
        this.clientCreditNumber = clientCreditNumber;
        this.occupied = false;
        this.lineNumber = -1;
        this.alive = true;
    }

    /**
     * the method checks for available seats to each individual required client.
     * in case an available sequence is found, cinema hall is updated with client details and a connection 
     * with the credit company is established forwarding the data needed to proceed.
     */
    public void run(){
        int ticketCount=0;
        int startSeat = -1;
        int endSeat = -1;
        for(int i=0 ; i<cinema.getCinemaHall().length && !occupied; i++){
            for(int j=0 ; j<cinema.getCinemaHall().length && !occupied; j++){
                if(cinema.getCinemaHall()[i][j]>0)
                    ticketCount++;
                else
                    ticketCount=0;
                if(ticketCount == requiredTickets){
                    lineNumber = i;
                    startSeat = j-requiredTickets+1;
                    endSeat = j;
                    occupied=true;
                }
            }
            for(int k=startSeat ;k<=endSeat ; k++)
                cinema.getCinemaHall()[lineNumber][k] = clientNumber;
            }
        if(occupied){
            // connection with credit company



        }
        this.alive = false;
    }
    public boolean status(){
        return this.alive;
    }
}

You don't need to transfer a DataOutputStream. Use Socket.getOutputStream() .

server side

public static void main(String[] args) throws IOException{
    // ... ...
    // Socket s = server.accept();
    DataOutputStream dos = new DataOutputStream(s.getOutputStream());
    // ... ...
    Thread cinemaThread = new CinemaThread( /* ... */, dos);
    // ... ...
}

public CinemaThread(/* ... */, DataOutputStream dos){
    // ... ...
    this.dos = dos;
}

public void run(){
    // ... ...
    if(occupied)
        dos.writeBoolean(true);
    else
        dos.writeBoolean(false);
    // ... ...
}

流通常是“输出”或“输入”的一种方式,因此,根据我对问题的阅读,不可能两种都使用一个流。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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