简体   繁体   English

使套接字等待来自JTextArea的输入

[英]Make socket wait for input from JTextArea

I am trying to learn a bit more about networking, sockets, udp etc.. 我正在尝试学习有关网络,套接字,udp等的更多信息。

// 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 ). (我有一个ServerSocket可以在localhost上正常运行)。 However now I am trying to do this by GUI, not by commandline. 但是现在我试图通过GUI而不是命令行来做到这一点。

I have a simple JTextArea, and a JButton. 我有一个简单的JTextArea和一个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? 每当我按下Jbutton并从JTextArea打印文本时,如何调用clientSocketOutputStream?

Shall I put a dead while(true) loop just to make sure the socket is waiting? 我是否应该为了确保套接字正在等待而放置一个死的while(true)循环? 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. 您还可以在按键上添加事件(例如,回车键)以触发发送和移动到历史记录的过程。

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

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