此EchoServer类的Client类应该是什么?

时间:2018-10-24 21:38:16

标签: java multithreading sockets serversocket

我正在尝试编写此EchoServer的Client类,以便服务器可以回显我的输入。看来EchoServer只能读取客户端的输入并打印它,而无需再次回显它。

这是EchoServer类。

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EchoServer implements Runnable {
    Socket socket;

    public EchoServer(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        System.out.printf("connection received from %s\n", socket);
        try {
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            Scanner in = new Scanner(socket.getInputStream());

            while (in.hasNextLine()) {
                String line = in.nextLine();
                System.out.printf("%s says: %s\n", socket, line);
                pw.printf("echo: %s\n", line);
                pw.flush();
            }

            pw.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(4343);
        System.out.printf("socket open, waiting for connections on %s\n",serverSocket);

        while (true) {
            Socket socket = serverSocket.accept();
            EchoServer server = new EchoServer(socket);
            new Thread(server).start();
        }
    }

}

这是我的EchoClient类,它读取系统输入并将其写入套接字。

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

public class EchoClient {
    Socket socket;
    private Scanner in;
    private PrintWriter out;

    public EchoClient(String address, int port) {
        try {
            socket = new Socket(address, port);
            System.out.println("Connected!");
            in = new Scanner(System.in);
            out = new PrintWriter(socket.getOutputStream());
        } catch (UnknownHostException u) {
            System.out.println(u);
        } catch (IOException e) {
            System.out.println(e);
        }

        String line = "";
        while (!line.equals("over")) {
            line = in.nextLine();
            out.println(line);
        }
        out.close();

    }

    public static void main(String[] args) throws IOException {
        EchoClient c1 = new EchoClient("127.0.1.1", 4343);
        EchoClient c2 = new EchoClient("127.0.1.1", 4343);

    }
}

EchoServer的Printwriter似乎没有编写echo语句。我想知道为什么吗?

0 个答案:

没有答案