You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java客户端-服务器通信out.println输出延迟问题求助

服务器响应延迟问题求助

我搞不懂为什么服务器没法正常向客户端输出内容。我Java经验不算丰富,能想到的办法都试过了。Add/List命令这类功能运行正常,但服务器响应总是滞后,要输入多次内容才会输出信息。

可以看到服务器响应滞后一两次输入

客户端代码

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, use Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.tcpechoclient;
import java.io.*;
import java.net.*;

/**
 *
 * @author Leepe
 */
public class TCPEchoClient {
 private static InetAddress host;
    private static final int PORT = 1248;

    public static void main(String[] args) {
     try 
     {
        host = InetAddress.getLocalHost();
     } 
     catch(UnknownHostException e) 
     {
    System.out.println("Host ID not found!");
    System.exit(1);
     }
     run();
   }
   
   private static void run() {
    Socket link = null;             //Step 1.
    try 
    {
    link = new Socket(host,PORT);       //Step 1.
        //link = new Socket( "192.168.0.59", PORT);
    BufferedReader in = new BufferedReader(new InputStreamReader(link.getInputStream()));//Step 2.
    PrintWriter out = new PrintWriter(link.getOutputStream(),true);  //Step 2.

    //Set up stream for keyboard entry...
    BufferedReader userEntry =new BufferedReader(new InputStreamReader(System.in));
    String message = "";
        String response = "";

        while (!message.equals("Stop")) {
                       
            System.out.println("Enter message to be sent to server: ");
            message =  userEntry.readLine();
            
            out.println(message);       //Step 3.
            //  out.flush();
            
            response = in.readLine();       //Step 3.
            System.out.println("\nSERVER RESPONSE> " + response);

        }
     }
    catch(IOException e)
    {
    e.printStackTrace();
    } 
    finally 
    {
        try 
        {
            System.out.println("\n* Closing connection... *");
            link.close();               //Step 4.
    }catch(IOException e)
        {
            System.out.println("Unable to disconnect/close!");
            System.exit(1);
    }
    }
 } // finish run method
}  //finish the class

服务器主类代码

/*
 * To change this license header, use License Headers in Project Properties.
 * To change this template file, use Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.tcpechoserverthreads;
import java.io.*;
import java.net.*;

/**
 *
 * @author Leepe
 */
public class TCPEchoServer { 
  private static ServerSocket servSock;
  private static final int PORT = 1248;
  private static int clientConnections = 0;

  public static void main(String[] args) {
    System.out.println("Opening port..."+"\n"+"Listening on port: "+PORT);
    try 
    {
        servSock = new ServerSocket(PORT);      //Step 1.
    }
    catch(IOException e) 
    {
         System.out.println("Unable to attach to port!");
         System.exit(1);
    }
    
    do 
    {
         run();
    }while (true);

  }
  
  synchronized private static void run()
  {
    Socket link = null;                        //Step 2.
    try 
    {
        link = servSock.accept(); 
        clientConnections++;
        String client_ID = clientConnections + "";
        Runnable resource = new ClientConnectionRun(link, client_ID);
        Thread t = new Thread (resource);
        t.start();
        
    }
    catch(IOException e1)
    {
        e1.printStackTrace();
        try {
        System.out.println("\n* Closing connection... *");
            link.close();                   //Step 5.
    }
       catch(IOException e2)
       {
            System.out.println("Unable to disconnect!");
        System.exit(1);
       }
    }
  } // finish run method 
} // finish the class

客户端连接线程代码

/*
 * To change this license header, use License Headers in Project Properties.
 * To change this template file, use Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.tcpechoserverthreads;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;

/**
 *
 * @author Leepe
 */
public class ClientConnectionRun implements Runnable {
    Socket client_link = null;  
    String clientID;
    public static List<String> currentList = new ArrayList<String>();
    String[] parts;
    String part1;
    String part2;
    String part3;
    String message = "";
    
    public ClientConnectionRun(Socket connection, String cID) {
        this.client_link = connection;
        clientID = cID;     
  }
    
    @Override
    synchronized public void run() {
        try{
            
            BufferedReader in = new BufferedReader( new InputStreamReader(client_link.getInputStream())); //Step 3.
            PrintWriter out = new PrintWriter(client_link.getOutputStream(),true); //Step 3.
            
            System.out.println("\n* started connection with the client " + clientID + " ... *");

           while (!message.equals("Stop")){//Step 4.
                
                message = in.readLine(); 
                
               // out.flush();
                System.out.println("\n Message received from client: " + clientID + " - " + message);
                out.println("\n Echo Message: " + message);
                //out.flush();
                if(message.contains(";")){
                                        // String userinput = message;
                                        // String item = message;   
                                             

                                           // System.out.println("Contains ;");

                                            String[] parts = message.split(";");
                                            String part1 = parts[0]; 
                                            String part2 = parts[1];
                                            
                                            System.out.println(part1);
                                            System.out.println(part2);
                                            
                                            if(parts.length >= 3 && part1.equals("add")){
                                                String part3 = parts[2]; 
                                            
                                             

                                            System.out.println(part1);
                                            System.out.println(part2);
                                            System.out.println(part3);
                                            
                                            currentList.add(part2+" - "+part3);
                                            //AddItem();

                                            }
                                            
                                            else if(parts.length <= 2 && part1.equals("list") ){ 
                                                
                                            
                                            System.out.println("list command working");
                                            //ListItem();
                                            
                                            System.out.println();
                                            System.out.println("----------------------");       
                                            System.out.println("To-Do List");
                                            System.out.println("----------------------");
                                            int number = 0;
                                             for (Iterator<String> it = currentList.iterator(); it.hasNext();) {
                                                
                                                message = it.next();
                                                 if(message.contains(part2)){
                                                     System.out.println(++number + " " + message);
                                                 }
                                             }
                                                System.out.println("----------------------");

                                            }
                                            else {
                                                System.out.println("\n Don't add a description if you are searching for a date");
                                            }
                                            
                                        }
                else if(!message.contains(";")){
                    System.out.println("\n Unknown command, Try using 'add' or 'list' followed by a ' ; ' as listed above ");
                }

           }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        
        finally 
        {
            try {
                System.out.println("\n* Closing connection with the client " + clientID + " ... *");
                client_link.close();                    //Step 5.
            }
            catch(IOException e)
            {
                System.out.println("Unable to disconnect!");
            }
        }
    }
}

我希望服务器能及时向已连接的客户端输出信息,现在的情况是服务器最终会输出,但需要输入多次内容才会响应,不清楚延迟原因,求帮忙解决。

内容的提问来源于stack exchange,提问作者Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:20:32