传输DataOutputStream

时间:2013-04-21 05:53:08

标签: java dataoutputstream

我有一个程序通过套接字将客户端线程连接到电影院。     客户转移他的详细信息(客户编号,所需的门票)影院在另一个线程中处理请求,以确保有足够的座位可用。     正如您将在代码中看到的那样,我在确定如何从影院(服务器)向客户端发送反馈时遇到了一些问题,所提供的代码未完成,我只想让您了解它的外观。     我的想法是将dataOutputStream传输到cinemaThread,当它完成后,影院线程会通过流将反馈返回给客户端是否可能?

客户端

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

服务器端

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

        }
    }
}

影院主题

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

2 个答案:

答案 0 :(得分:2)

您无需传输 DataOutputStream。使用Socket.getOutputStream()

服务器端

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);
    // ... ...
}

答案 1 :(得分:1)

Streams通常只有一种“out”或“in”,所以通过我对这个问题的解读,不可能为这两个流使用一个流。