服务器未显示来自客户端的用户输入

时间:2019-12-02 11:14:59

标签: java sockets server client

这是我简单的Java套接字的代码。连接两个插座可以正常工作。但是,“发送消息”功能无法正常工作。从理论上讲,当我在客户端控制台中编写某些内容时,该消息应立即显示在服务器控制台中,而事实并非如此。仅在我写“ Bye”之后显示输入,因此在我停止连接之后。我在这里想念什么?

服务器:

import java.net.*;
import java.io.*;


public class Server { 
    //initialize socket and input stream 
    private Socket clientSocket = null; 
    private ServerSocket serverSocket = null; 
    private BufferedReader input =  null; 

    // constructor for server with Port
    public Server(int port) throws IOException { 

       // start server and wait for Conncection from client
       serverSocket = new ServerSocket(port); 
       System.out.println("Server started\nWaiting for Client..."); 

       // accept connectionrequest from client
       clientSocket = serverSocket.accept(); 
       System.out.println("Client accepted"); 

       // take input from client
       input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 

       // read input until "Bye"
       String line = "";
       while (!line.equals("Bye")) { 
           line = input.readLine(); 
           System.out.println(line); 
       } 

       // close connection
       System.out.println("Closing connection"); 
       clientSocket.close(); 
       input.close(); 
   }

   public static void main(String args[]) throws IOException { 
       Server server = new Server(4999); 
   } 

}

客户:

import java.net.*; 
import java.io.*;

public class Client { 
    // Clientsocket, Input, Output
    private Socket clientSocket = null; 
    private BufferedReader input = null; 
    private PrintWriter output = null; 

    // constructor for Client with IP-Adress and Port   
    public Client(String address, int port) throws IOException { 
        // Sendet Request an Server über IP und Port
        clientSocket = new Socket(address, port);                
        System.out.println("Connected"); 

        // take input from console
        input = new BufferedReader(new InputStreamReader(System.in));               
        // send output to socket
        output = new PrintWriter(clientSocket.getOutputStream(), true); 

        // read input, until "Bye"
        String line = ""; 
        while (!line.equals("Bye")) { 
            line = input.readLine(); 
            output.write(line); 
        } 
        // close connection
            input.close(); 
            output.close(); 
            clientSocket.close(); 
    } 

    public static void main(String args[]) throws IOException { 
        Client client = new Client("localhost", 4999); 
    } 
} 

0 个答案:

没有答案