简体   繁体   English

Java套接字客户端服务器响应应用程序

[英]Java socket client server response application

I am trying to write a simple client server which will echo back the users request with the string “Response : ” appended to it. 我正在尝试编写一个简单的客户端服务器,该服务器将回显附加了字符串“ Response:”的用户请求。

Their are similar questions up that i have looked at but i am having trouble understanding what is going on. 我看过他们的类似问题,但我无法理解发生了什么。 I am trying to write this but cant get it to work. 我正在尝试编写此文件,但无法使其正常工作。 Mainly because I am very confused about what is happening. 主要是因为我对正在发生的事情感到非常困惑。

I Have commented my code as best i could to try explain what i think is happening. 我已尽我所能来注释我的代码,以尝试解释我的想法。 I am not sure what the problem is when i run this and enter a message i do not get a response 我不确定运行此问题并输入消息时没有什么反应,但没有得到答复

Client 客户

public class Client {

public void go() {

    try {
        //Create a Socket with ip and port number
        Socket s = new Socket("127.0.0.1", 4242);

        //Get input from user
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter a message");
        String clientMessage = in.nextLine();

        //Make a printwriter and write the message to the socket
        PrintWriter writer = new PrintWriter(s.getOutputStream());
        writer.write(clientMessage);
        writer.close();

        //StreamReader to read the response from the server
        InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
        BufferedReader reader = new BufferedReader(streamReader);

        //Get the response message and print it to console
        String responseMessage = reader.readLine();
        System.out.println(responseMessage);
        reader.close();

    } catch (IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }

}

public static void main(String[] args) {
    Client c = new Client();
    c.go();
}

}

Server 服务器

public class Server {

public void go() {
    try {
        //Make a ServerSocket to listen for message
        ServerSocket ss = new ServerSocket(4242);

        while (true == true) 
        {
            //Accept input from socket
            Socket s = ss.accept();

            //Read input from socket
            InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
            BufferedReader reader = new BufferedReader(streamReader);                
            String message = reader.readLine();

            //get the message and write it to the socket as response
            PrintWriter writer = new PrintWriter(s.getOutputStream());
            String response = "Response : " + message;
            writer.println(response);
            writer.close();

        }
    } catch (IOException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public static void main(String[] args) {
    Server server = new Server();
    server.go();
}

}

Remove sock and serverSock from your client code and use s.getInputStream. 从客户端代码中删除sock和serverSock并使用s.getInputStream。

Socket is bi-directional on both sides, so just as you do not need a new one on the server when sending back the message, you do not need a new one for receiving it on the client either. 套接字在两侧都是双向的,因此就像在发送回消息时不需要服务器上的新套接字一样,您也不需要在客户端上接收新消息的套接字。

EDIT 编辑

Also, "Closing the returned OutputStream will close the associated socket." 另外,“关闭返回的OutputStream将关闭关联的套接字。” (docs for getOutputSteam), so do not close the writer, just flush it. (有关getOutputSteam的文档),因此请不要关闭编写器,只需刷新它即可。

Server can work in its current form, and Client starts working with the minor changes (println and flush): Server可以其当前形式工作,并且Client开始进行较小的更改(println和flush):

//Create a Socket with ip and port number
Socket s = new Socket("127.0.0.1", 4242);

//Get input from user
Scanner in = new Scanner(System.in);
System.out.println("Please enter a message");
String clientMessage = in.nextLine();

//Make a printwriter and write the message to the socket
PrintWriter writer = new PrintWriter(s.getOutputStream());
writer.println(clientMessage); // <- println
writer.flush();                // <- flush

//StreamReader to read the response from the server
InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);

//Get the response message and print it to console
String responseMessage = reader.readLine();
System.out.println(responseMessage);
reader.close();
writer.close();                // <- new location for close (*)

(*) Using close inside the main try block is not considered safe, as whenever there is an exception, these lines just will not run (also, if you use any kind of smart IDE, it probably points out that the Socket object itself, and the Scanner are not closed at all). (*)在主try块内使用close是不安全的,因为只要有例外,这些行就不会运行(此外,如果您使用任何类型的智能IDE,它可能会指出Socket对象本身,并且扫描仪根本没有关闭)。 Further reading: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html 进一步阅读: https : //docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

So at the end the Client could rather look like this, following a more "contemporary" approach: 因此,最终,客户可能更喜欢采用“当代”方法:

try (
    Socket s = new Socket("127.0.0.1", 4242);
    Scanner in = new Scanner(System.in);
    PrintWriter writer = new PrintWriter(s.getOutputStream());
    InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
    BufferedReader reader = new BufferedReader(streamReader);
) {
    //Create a Socket with ip and port number

    //Get input from user
    System.out.println("Please enter a message");
    String clientMessage = in.nextLine();

    //Make a printWriter and write the message to the socket
    writer.println(clientMessage);
    writer.flush();

    //StreamReader to read the response from the server

    //Get the response message and print it to console
    String responseMessage = reader.readLine();
    System.out.println(responseMessage);
} catch (IOException ex) {
    ex.printStackTrace(); // (**)
}

(**) I am absolutely sure that you have not checked the log, otherwise you would have known about closing the Socket prematurely. (**)我绝对可以确定您没有检查日志,否则您可能早已知道要关闭Socket。 When experimenting with small pieces of code, I would not suggest hiding the exceptions in obscure logs. 在尝试一小段代码时,我不建议在模糊的日志中隐藏异常。 In fact I usually just write "throws Exception" everywhere (including main , that is possible too) and let JRE dump everything into my face. 实际上,我通常只是到处写“ throw Exception”(包括main ,这也是可能的),然后让JRE将所有内容转储到我的脸上。

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

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