如何在中间通信时关闭缓冲读卡器

时间:2015-03-05 12:35:27

标签: java

我需要一个bufferread来处理客户端,当客户端关闭“CLOSE”时会关闭。客户端关闭,一旦通过它发送消息,我就无法让服务器关闭。 以下是我的代码: `

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

    class TCPClient2 {

    public static void main(String argv[]) throws Exception {
        String sentence;
        String modifiedSentence;

        BufferedReader inFromUser
                = new BufferedReader(new InputStreamReader(System.in));

        Socket clientSocket = new Socket("143.53.30.136", 49250);//port number and ip address of client

        DataOutputStream outToServer
                = new DataOutputStream(clientSocket.getOutputStream());

        InputStream sin = clientSocket.getInputStream();

        // Just converting them to different streams, so that string handling becomes easier.
        DataInputStream inFromServer = new DataInputStream(sin);

        try {

            do {

                System.out.print("Enter message : ");
                sentence = inFromUser.readLine();

                outToServer.writeBytes(sentence + '\n');

                //Question B4
                //if statement for closing the socket connection 
                if (sentence.equals("CLOSE")) {
                    clientSocket.close();
                    //closes client socket
                    System.out.println("Socket Closed");
                    //prints socket closed to tell user socket has closed
                    System.exit(0);

                }

                outToServer.writeBytes(sentence + '\n');
                System.out.print("Message sent! please wait for server     message:  ");
                modifiedSentence = inFromServer.readUTF();

                System.out.println("FROM SERVER: " + modifiedSentence);

            } while (!sentence.equals("CLOSE"));
        } catch (IOException e) {
        }
        clientSocket.close();
    }
}`

和服务器:

`

       /*
     chris and paul
     */
import java.io.*; 
import java.net.*; 
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class TCPMultiThreadServer { 


    private static ServerSocket welcomeSocket;

    //port number the server is using
    private static final int PORT = 49250;
    private static int clientNo =1;
    public static void main(String argv[]) throws Exception 
    { 

        System.out.println("Opening port...\n");

        try
    {
           // ServerSocket listens for new connections on specified port
           welcomeSocket = new ServerSocket(PORT);



            do
            { 

                Socket client = welcomeSocket.accept();

                System.out.println("\nNew client accepted.\n");
            //Create a thread to handle communication with
        //this client and pass the constructor for this
        //thread a reference to the relevant socket...
                TCPMultiThreadServer.ClientHandler handler = 
                new TCPMultiThreadServer().new ClientHandler(client,clientNo);

                handler.start(); // Calls run() method in ClientHandler

                clientNo++; 

        } while (true);

        } catch (IOException e) {}
    }


// Original work not credited
class ClientHandler extends Thread
{
        private Socket client;

        private BufferedReader inFromClient;
        private BufferedReader text_to_Client;
        private DataOutputStream outToClient;
       private FileWriter Filestream;
        private BufferedWriter out;

        public int clientNo;

        public boolean stopping;

        //part A question 4, adding buffer string array to the program

        private String[] buffer; //creation of buffer string array.

        private int bufferI; // Index of the last thing inserted into the array

    public ClientHandler(Socket socket, int clientNos)
    {

            //Set up reference to associated socket
            client = socket;
            clientNo= clientNos;

            try
            {   
                 // Gets access to input/output stream of socket
                 inFromClient =
                 new BufferedReader(new InputStreamReader
                 (client.getInputStream()));
                 text_to_Client =
                 new BufferedReader(new InputStreamReader(System.in));
                 outToClient = 
                 new DataOutputStream(client.getOutputStream()); 

            } catch(IOException e) {}
    }

    public void run()
    {

            try
            {
        stopping = false;

                 //Question A4 buffer continued
                buffer = new String[4]; 
                //generates buffer string array containing 4 strings
                bufferI = 0;
                //  make sure bufferIndex =  0
        String clientSentence; 
        Thread mythread = Thread.currentThread(); 



                do
                {
                    //Accept message from client on socket's input stream
                    OutputStream sout = client.getOutputStream();

                    // Just converting them to different streams, so that string
                    // handling becomes easier.
                    DataOutputStream text_to_send = new      DataOutputStream(sout);

                    clientSentence = inFromClient.readLine();


                    System.out.println("Message received from client number " +
                            clientNo + ": "+ clientSentence);



                    // String to be scanned to find the pattern.
      String line = clientSentence;
      String pattern = "[C][L][O][S][E]";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      //if (m.find( )) {
        // System.out.println("Found value: " + m.find() );
        // System.out.println("Found value: " + m.group(1) );
         //System.out.println("Found value: " + m.group(2) );
      //} else {
       //  System.out.println("NO MATCH");
      //} 
                  //part B question 4 close command 
                    //if statement for closing the socket connection if it is equal to close
                    if(m.matches()) 
                    { //prints socket closed to tell user socket has closed
                        System.out.println("Socket connection to client number "
                                + clientNo + " closed");


                        try
                        {







                        } catch(Exception e) {}

            out.flush();
                        out.close(); // Close the file handler
                        client.close(); // Close the connection with the client,

                        clientNo--; // Decrement the number of clients
                    }
                    else 
                    {
                 //part A question 4, adding buffer string array to the program
                        // looks to see if the buffer string array is full
                       //and also looks to see if  bufferIndex is in range
                        if (bufferI > buffer.length-1) 
            {   
                            // Print BUFFER FULL
                            System.out.println("BUFFER FULL");
                            // Clear clientSentence string
                            clientSentence = " "; 

                            // For loop which travels through the buffer array of string
                            for (int i=0; i<buffer.length; i++)
                            {
                               // Append buffer element to clientSentence string
                               clientSentence += buffer[i] + " , "; 
                               buffer[i] = null; // makes the buffer null

                            }

                            bufferI = 0; // Reset bufferI back to 0 so writing to the buffer can restarted

                            // prints buffer cleared  back to the clients
                            text_to_send.writeUTF("BUFFER CLEARED :" +
                                    clientSentence); 

                        }
                        else
                        {
                            buffer[bufferI] = clientSentence;
                            System.out.println("Buffer " + bufferI+ ": " +
                                    buffer[bufferI]);



                            bufferI++;
                            System.out.println("Enter Message: ");
                            // Reads message from server interface
                            // and sends it to the client
                            clientSentence = text_to_Client.readLine();

                            text_to_send.writeUTF(clientSentence);
                            System.out.println("Your message: " +
                                    clientSentence);


                        }
                    }
                    if (mythread.activeCount() == 2 &&
                            (clientNo ==0 || clientNo >0) &&
                                clientSentence.equals("CLOSE"))
                    {

                        System.exit(0);
                    }

                } while(!clientSentence.equals("CLOSE"));

                 client.close();

        } catch(IOException e) {} 

          } 
      } 
  }
`

0 个答案:

没有答案