Java Socket为什么服务器不能回复客户端 [英] Java Socket why server can not reply client

查看:31
本文介绍了Java Socket为什么服务器不能回复客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写代码让客户端向服务器发送字符串,服务器打印字符串并回复字符串,然后客户端打印字符串服务器回复.
我的服务器

I wanna write the code to let Client send a string to Server, Server print the string and reply a string, then Client print the string Server reply.
My Server

public class Server {

public static void main(String[] args) throws IOException {
    ServerSocket ss = null;
    Socket s = null;
    try {
        ss = new ServerSocket(34000);
        s = ss.accept();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());

        while (true) {
            String string = in.readLine();
            if (string != null) {
                System.out.println("br: " + string);

                if (string.equals("end")) {
                    out.write("to end");
                    out.flush();
                    out.close();
                    System.out.println("end");
                    // break;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        s.close();
        ss.close();
    }
}
}

我的客户:

public class Client {
public static void main(String[] args) {
    Socket socket =null;


    try {
        socket = new Socket("localhost", 34000);
        BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
        OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());

        String string = "";
        string = "end";
        out.write(string);
        out.flush();
        while(true){
            String string2 = in.readLine();
            if(string2.equals("to end")){
                System.out.println("yes sir");
                break;
            }
        }


    }  catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            System.out.println("closed client");
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
}

有什么问题吗?如果我删除客户端类中的代码while(true) ...",就可以了.

are there some somethings wrong? if i remove the code "while(true) ..." in client class, it's OK.

推荐答案

你应该在写入流的String的末尾添加" ".

you should add " " at the end of the String which write into stream.

示例:

客户:

    string = "end";
    out.write(string + "
");
    out.flush();

服务器:

    out.write("to end" + "
");
    out.flush();
    out.close();
    System.out.println("end");
                // break;

这篇关于Java Socket为什么服务器不能回复客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆