如何在Java中使用客户端 - 服务器应用程序读写多行代码

时间:2017-12-22 10:17:26

标签: java multithreading client-server

我有一个多线程Java客户端 - 服务器应用程序,发现自己正在努力进行多线通信。这就是我的意思

如果我写这样的服务器:

private static void startHandler(final Socket socket)
    {
        Thread thread = new Thread()
        {
            @Override
            public void run()
            {
                try {
                    Scanner inputFromUser = new Scanner(socket.getInputStream());
                    PrintStream outPutToUser = new PrintStream(socket.getOutputStream(), true);
                    outPutToUser.println("Welcome!");
                    System.out.println(inputFromUser.nextLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

    }

像这样编写客户端:

public static void main(String[] args) throws Exception
    {
        Scanner inputFromUser = new Scanner(System.in);
        Socket socket = new Socket("127.0.0.1", 5555);
        Scanner inputFromServer = new Scanner(socket.getInputStream());
        PrintStream outputToServer = new PrintStream(socket.getOutputStream());
        String greetingFromServer = inputFromServer.nextLine();
        System.out.println(greetingFromServer);
        outputToServer.println(inputFromUser.nextLine());
    }

效果很好:

  • 服务器向客户端发送“欢迎”

  • 用户输入一些字符串

  • 此字符串将在服务器控制台中打印

但如果我试图让它变得更加复杂:

private static void startHandler(final Socket socket)
    {
        Thread thread = new Thread()
        {
            @Override
            public void run()
            {
                try {
                    Scanner inputFromUser = new Scanner(socket.getInputStream());
                    PrintStream outPutToUser = new PrintStream(socket.getOutputStream(), true);
                    outPutToUser.println("Welcome!");
                    sendInitialCommandsToUser(outPutToUser);
                    System.out.println(inputFromUser.nextLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

    }

    private static void sendInitialCommandsToUser(PrintStream writer)
    {
        writer.println("1 - Log In");
        writer.println("2 - Sign up");
        writer.println("3 - Exit");
    }

客户端:

public static void main(String[] args) throws Exception
    {
        Scanner inputFromUser = new Scanner(System.in);

        Socket socket = new Socket("127.0.0.1", 5555);
        Scanner inputFromServer = new Scanner(socket.getInputStream());
        PrintStream outputToServer = new PrintStream(socket.getOutputStream());

        String greetingFromServer = inputFromServer.nextLine();
        System.out.println(greetingFromServer);

        getMultipleLinesFromServer(inputFromServer);

        outputToServer.println(inputFromUser.nextLine());
    }

    private static void getMultipleLinesFromServer(Scanner scanner)
    {
        while(scanner.hasNextLine())
        {
            System.out.println(scanner.nextLine());
        }
    }

它被getMultipleLinesFromServer(Scanner scanner)方法

所困扰

客户端输出仅

Welcome!
1 - Log In
2 - Sign up
3 - Exit

我无法提供要在服务器上打印的字符串..有什么问题?

2 个答案:

答案 0 :(得分:1)

如果你想逐行阅读,BufferedReader是一个不错的选择

试试这个,在我的IDEA上运作良好

package com.zhouplus;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    private static void startHandler(final Socket socket) {
        Thread thread = new Thread(() -> {
            try {
                BufferedReader inputFromUser = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter outPutToUser = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                outPutToUser.println("Welcome!");
                sendInitialCommandsToUser(outPutToUser);
                System.out.println("start readline!");
                System.out.println(inputFromUser.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }

    private static void sendInitialCommandsToUser(PrintWriter writer) {
        writer.println("1 - Log In");
        writer.println("2 - Sign up");
        writer.println("3 - Exit");
        writer.flush();
    }

    public static void main(String[] argv) throws IOException {
        ServerSocket ss = new ServerSocket(5555);
        Socket accept = ss.accept();
        startHandler(accept);
    }
}

和客户

package com.zhouplus;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws Exception {
        Scanner inputFromUser = new Scanner(System.in);

        Socket socket = new Socket("localhost", 5555);
        BufferedReader inputFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter outputToServer = new PrintWriter(socket.getOutputStream());


        String greetingFromServer = inputFromServer.readLine();
        System.out.println(greetingFromServer);

        new Thread(() -> {
            String str = inputFromUser.nextLine();
            outputToServer.println(str);
            outputToServer.flush();
        }).start();

        getMultipleLinesFromServer(inputFromServer);
    }

    private static void getMultipleLinesFromServer(BufferedReader br) throws IOException {
        String str;
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
        System.out.println("over");
    }
}

答案 1 :(得分:0)

如果你看一下Scanner hasNextLine方法的Javadocs ......

@ManyToOne(fetch = FetchType.LAZY, optional = true)

看来,一旦打印出“3 - Exit”,它就会阻止等待来自服务器的更多数据。