Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在通信中途关闭缓冲读卡器_Java - Fatal编程技术网

Java 如何在通信中途关闭缓冲读卡器

Java 如何在通信中途关闭缓冲读卡器,java,Java,我需要一个bufferread来与一个在单词关闭时关闭的客户端一起工作。客户端关闭了,我只是无法让服务器在通过它发送消息后关闭。 以下是我的代码: ` 和服务器: ` clientsentance中是否有新行字符?您可能希望看到这一点,以了解如何检测套接字何时关闭No to close I type close,如果未发送或接收任何消息,该功能将正常工作,但我希望它在我键入close时随时关闭端口。我通过了这项任务,只是让它结束了,所以顺便说一下。我只是想知道是否有任何方法可以出于我自己的兴趣来

我需要一个bufferread来与一个在单词关闭时关闭的客户端一起工作。客户端关闭了,我只是无法让服务器在通过它发送消息后关闭。 以下是我的代码: `

和服务器:

`


clientsentance中是否有新行字符?您可能希望看到这一点,以了解如何检测套接字何时关闭No to close I type close,如果未发送或接收任何消息,该功能将正常工作,但我希望它在我键入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) {} 

          } 
      } 
  }
`