2

刚刚开始学习本教程的这一部分。我只对端口是什么等有一个基本的了解。

我试图运行这段代码:

import java.io.*;
import java.net.*;

public class EchoClient {
    public static void main(String[] args) throws IOException {

        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            echoSocket = new Socket("taranis", 7);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                                        echoSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection to: taranis.");
            System.exit(1);
        }

        BufferedReader stdIn = new BufferedReader(
                               new InputStreamReader(System.in));
        String userInput;

    while ((userInput = stdIn.readLine()) != null) {
        out.println(userInput);
        System.out.println("echo: " + in.readLine());
    }

    out.close();
    in.close();
    stdIn.close();
    echoSocket.close();
    }
}

“不知道主机:taranis。Java 结果:1”

是我得到的错误捕获。根据我有限的理解;回声服务器是我机器上存在的东西吗?如果是这种情况,我需要做什么才能让它运行?还是我走远了?还有为什么他们选择“taranis”作为参数?

我还用“localhost”替换了“taranis”,看看发生了什么。这次它最终捕获了 IOException。

编辑:所以我发现在win7中默认禁用回显服务器并激活它。但是我什至无法在 telnet 上连接到它。我想我可能只是在我的头上。我也试过你推荐的插座,但没有成功。

4

2 回答 2

2

从同一个教程:

...这里使用的 Socket 构造函数需要机器的名称和要连接的端口号。示例程序使用主机名 taranis。这是我们本地网络上的假设机器的名称。当您在您的机器上输入并运行此程序时,请将主机名更改为您网络上的机器的名称。确保您使用的名称是您要连接的机器的完全限定 IP 名称。第二个参数是端口号。端口号 7 是 Echo 服务器侦听的端口。

在任何情况下,您都可能希望将 taranis 更改为"localhost"并确保在您的计算机上运行 echo 服务。如果不是,您可以使用类似以下代码的代码来模拟回显服务器。

import java.net.Socket;
import java.util.Formatter;
import java.util.Scanner;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EchoServer {

    public static void main(String[] args) {
        try {
            new EchoServer(INSERTPORT).execute();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private ServerSocket serverSocket;
    private int port;

    private ArrayList<Client> clientList;
    private ExecutorService clientRunner;

    public EchoServer(int port) throws IOException {
        this.port = port;
        serverSocket = new ServerSocket(port);
        clientRunner = Executors.newCachedThreadPool();
        clientList = new ArrayList<>();
    }

    public void sendMessageToAll(String message) {
        for (Client c : clientList) {
            c.displayMessage(message);
        }
    }

    public void execute() throws IOException {
        while (true) {
            clientList.add(new Client(serverSocket.accept(), this));
            clientRunner.execute(clientList.get(clientList.size()-1));
        }
    }
    private class Client implements Runnable {

        private Socket clientSocket;
        private Scanner input;
        private Formatter output;

        public Client(Socket s) throws IOException {
            clientSocket = s;

            input = new Scanner(clientSocket.getInputStream());
            output = new Formatter(clientSocket.getOutputStream());
        }

        public void displayMessage(String s) {
            output.format(s + "\n");
            output.flush();
        }
        @Override
        public void run() {
            while(clientSocket.isConnected()) {
                if(input.hasNextLine()) {
                    sendMessageToAll(input.nextLine());
                }
            }
        }
    }
}

编辑:为了完整起见,正如您提到运行代码的一些问题,您运行服务器(此代码)并使其在后台运行,然后运行客户端(您发布的代码)。我测试过,效果很好。

于 2012-06-18T02:35:38.733 回答
0

试试这个,

  1. 使用127.0.0.1 的环回地址而不是 taranis。

  2. 使用高于 1024 的端口,例如 4444、8333 等......

我还添加了我用来学习客户端服务器通信的代码

客户端代码:

public class ClientWala {

    public static void main(String[] args) throws Exception{

        Boolean b = true;
    Socket s = new Socket("127.0.0.1", 4444);

    System.out.println("connected: "+s.isConnected());


    OutputStream output = s.getOutputStream();
    PrintWriter pw = new PrintWriter(output,true);

    // to write data to server
    while(b){

        if (!b){

             System.exit(0);
        }

        else {
            pw.write(new Scanner(System.in).nextLine());
        }
    }


    // to read data from server
    InputStream input   = s.getInputStream();
    InputStreamReader isr = new InputStreamReader(input);
    BufferedReader br = new BufferedReader(isr);
    String data = null;

    while ((data = br.readLine())!=null){

        // Print it using sysout, or do whatever you want with the incoming data from server

    }




    }
}

服务器端代码:

public class ServerTest {

    ServerSocket s;

    public void go() {

        try {
            s = new ServerSocket(44457);

            while (true) {

                Socket incoming = s.accept();
                Thread t = new Thread(new MyCon(incoming));
                t.start();
            }
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

    class MyCon implements Runnable {

        Socket incoming;

        public MyCon(Socket incoming) {

            this.incoming = incoming;
        }

        @Override
        public void run() {

            try {
                PrintWriter pw = new PrintWriter(incoming.getOutputStream(),
                        true);
                InputStreamReader isr = new InputStreamReader(
                        incoming.getInputStream());
                BufferedReader br = new BufferedReader(isr);
                String inp = null;

                boolean isDone = true;

                System.out.println("TYPE : BYE");
                System.out.println();
                while (isDone && ((inp = br.readLine()) != null)) {

                    System.out.println(inp);
                    if (inp.trim().equals("BYE")) {
                        System.out
                                .println("THANKS FOR CONNECTING...Bye for now");
                        isDone = false;
                        s.close();
                    }

                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                try {
                    s.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }

        }

    }

    public static void main(String[] args) {

        new ServerTest().go();

    }

}
于 2012-06-18T02:39:06.063 回答