简体   繁体   English

传输DataOutputStream

[英]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? 我的想法是将dataOutputStream传输到CinemaThread,完成后,电影院线程将通过流将反馈返回给客户端 ,这可能吗?

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. 您无需传输 DataOutputStream。 Use Socket.getOutputStream() . 使用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);
    // ... ...
}

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

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

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