まず、すべてのコードをお詫び申し上げますが、あまりにも多くのコードが十分でないように感じる。私はシンプルなチャットクライアントとプリントライターを作っています。特に苦労しています。コードを使用すると、今はサーバークラスとやりとりし、印刷したいものを完全に細かく印刷できます。しかし、私が 'writer.flush();'を削除すると、印刷を停止します。明らかに間違っている私の理解で、 'writer.println(outgoing.getText());'これはサーバーに送信しようとしているテキストを送信するのに十分なはずです。私はすべての情報を書き込むフラッシュ力を理解していますが、私は何を書いているのかまだ書いている時にこれがなぜ必要なのですか?Java - PrintWriterを理解し、フラッシュする必要がある
public class SimpleChatClientA {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public void go(){
JFrame frame = new JFrame("Ludicrously Simple Chat Client");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(400, 500);
frame.setVisible(true);
}//close go
public void setUpNetworking(){
try{
sock = new Socket("127.0.0.1", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("network established");
}catch(Exception e){
e.printStackTrace();
}
}//close setupnetworking
public class SendButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
try{
writer.println(outgoing.getText());
writer.flush();
}catch(Exception ex){
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}//close sendbuttonlistener inner class
public class IncomingReader implements Runnable{
public void run(){
String message;
try{
while((message = reader.readLine()) != null){
System.out.println("read " + message);
incoming.append(message + "\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
}//close inner class incomingreader
public static void main(String[] args){
new SimpleChatClientA().go();
}
}
事前のおかげで、私は私が私が適切にStackOverflowに投稿した最初の時間を教えてください与えることができた情報はもう存在している場合。
Ahh okありがとう、私はドキュメントを読んだが、何らかの理由でそれはかなりクリックしていなかったが、あなたの説明を広げて、それは多くの助けになった。ありがとう! – fdbdcbc