简体   繁体   中英

Make socket wait for input from JTextArea

I am trying to learn a bit more about networking, sockets, udp etc..

// main method: 

Socket clientSocket = new Socket("localhost", 10007);

PrintWriter clientSocketOutputStream = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader clientSocketInputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

Scanner userInputReader = new Scanner(System.in);
String providedInput;

while ((providedInput = userInputReader.nextLine()) != null) {
    clientSocketOutputStream.println(providedInput);
    displayOnConsole("You have provided text: " + providedInput);
    String responseFromTheServer = clientSocketInputStream.readLine();
    System.out.println("Server has responded: " + responseFromTheServer);
    System.out.println(waitingForInputText);
}

// rest of the code... 

So this little code I have works well. ( I have a ServerSocket which runs fine on localhost ). However now I am trying to do this by GUI, not by commandline.

I have a simple JTextArea, and a JButton. I am stuck at:

while ((providedInput = userInputReader.nextLine()) != null) 

How can I invoke the clientSocketOutputStream, everytime I hit the Jbutton and print the text from the JTextArea?

Shall I put a dead while(true) loop just to make sure the socket is waiting? Something tells me there must be another way.

Just put a listener on the the text area to detect when the content changes and then send whatever you like onto the output stream based on the change made.

In general a text area doesn't map well to this though as a text area you can edit anywhere, you are probably better having a read only text area to display the history - and then having a single text entry box (or a smaller text area) and a button that you press to send everything in the smaller box on the screen out on the stream, append the sent text to the end of the history, and then wipe the smaller box.

You can also add an event on a key press (for example the return key) to trigger the send-and-move-to-history process.

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