简体   繁体   English

读写服务器

[英]Reading and Writing to Server

Objective: send data to server and have server return something back and to print what the server sends back 目标:将数据发送到服务器并让服务器返回一些内容并打印服务器发回的内容

Problem: If I close the out stream then it will send the data to the server but my input stream won't work and I can't receive what the server tries to give me. 问题:如果我关闭流出,那么它会将数据发送到服务器,但我的输入流将无法工作,我无法收到服务器试图给我的内容。 If I use flush() to send data to server the server never receives the data. 如果我使用flush()将数据发送到服务器,则服务器永远不会接收数据。 I have been stuck on this for literally 3 hours. 我已经坚持了3个小时。 How do you do read and Write at the same time. 你如何同时读写。

Client.java Client.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

class Client {
    public static void main(String args[]) {
        String data = "head";
        try {
            Socket skt = new Socket("server", 5050);
            PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            out.print(data);
            out.close();

            System.out.println("Sent data");
            while (!in.ready()) {
            }

            String input = in.readLine();
            System.out.println(input);

            out.close();
            in.close();
            skt.close();
        } catch (Exception e) {
            System.out.print("Whoops! It didn't work!\n" +e.toString());
        }
    }
}

Server.java Server.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.PrintWriter;

class Server {
    public static void main(String args[]) {
        String data;
        String input;
        try {
            ServerSocket srvr = new ServerSocket(5050);
            Socket skt = srvr.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    skt.getInputStream()));
            PrintWriter out = new PrintWriter(skt.getOutputStream(), true);

            // /////Waits for message from client/////////
            while (!in.ready()) {
            }
            // ///////////////////////////////////////////

            input = in.readLine(); // Read the message
            System.out.println("Received String input: " + input);
            // Send output to client
            System.out.println("After output");
            if (input.equals("head"))
                data = "haha";
            else
                data = "Wtf did you send me";
            Thread.sleep(2000);
            out.print(data);
            // ///////////////////

            System.out.println("Sent data: " + data);
            in.close();
            out.close();
            skt.close();
            srvr.close();
        } catch (Exception e) {
            System.out.print("Whoops! It didn't work!\n");
        }

    }
}

In your client you have: 在您的客户中,您有:

out.print(data);
out.close();

and in your server you have: 在您的服务器中,您有:

input = in.readLine();

Client send message without new line character - that's why in.ready() is true . 客户端发送没有换行符的消息 - 这就是in.ready()真的原因 What's more - it closes PrintWriter instead of flushing (you are also closing stream at the end of program). 更重要的是 - 它关闭PrintWriter而不是刷新(你也在程序结束时关闭流)。 If you change that lines to: 如果您将这些行更改为:

out.println(data); // sends message with new line character
out.flush();       // unnecessary

Client sends a message. 客户端发送消息。 The same thing is when Server sends message - you use print instead of println but Client reads using readLine that reads until new line character, or to be more precise ( BufferedReader|readLine() ): 同样的事情是当服务器发送消息时 - 你使用print而不是println但客户端使用readLine读取,直到新行字符读取,或者更精确( BufferedReader | readLine() ):

Reads a line of text. 读一行文字。 A line is considered to be terminated by any one of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return followed immediately by a linefeed. 一条线被认为是由换行符('\\ n'),回车符('\\ r')或回车符中的任何一个终止,后面紧跟换行符。

One more thing - you are connecting to the server using "server" hostname. 还有一件事 - 您使用"server"主机名连接到服务器。 For my tests I changed it to "localhost" . 对于我的测试,我将其更改为"localhost" Maybe there is other mistake? 也许还有其他错误?

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

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