简体   繁体   English

输入和输出无法解析为类型(Java套接字)

[英]In & Out Cannot be Resolved to a Type (Java Socket)

I really don't know what the problem is. 我真的不知道是什么问题。 I am learning Java and I am following Oracle's Docs on networking. 我正在学习Java,并且正在关注有关网络的Oracle文档。 I simply did a copy and paste for their example and get this error. 我只是为他们的示例复制并粘贴了该错误。 Could someone be kind enough to help? 有人可以帮助您吗? Thank you :) 谢谢 :)

Here's the code from Oracle: 这是Oracle的代码:

import java.net.Socket;
import java.net.ServerSocket;

public class EchoServer {

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

        // create socket
        int port = 4444;
        ServerSocket serverSocket = new ServerSocket(port);
        System.err.println("Started server on port " + port);

        // repeatedly wait for connections, and process
        while (true) {

            // a "blocking" call which waits until a connection is requested
            Socket clientSocket = serverSocket.accept();
            System.err.println("Accepted connection from client");

            // open up IO streams
            In  in  = new In (clientSocket);
            Out out = new Out(clientSocket);

            // waits for data and reads it in until connection dies
            // readLine() blocks until the server receives a new line from client
            String s;
            while ((s = in.readLine()) != null) {
                out.println(s);
            }

            // close IO streams, then socket
            System.err.println("Closing connection with client");
            out.close();
            in.close();
            clientSocket.close();
        }
    }
}

It seems you copied it wrong. 看来您复制错了。

I was able to run it on the first try. 我能够在第一次尝试中运行它。

echo: 
hi mom
echo: hi mom
how are you?
echo: how are you?

I took what they had and remixed it a bit to make it simpler (less code, and it does the same thing). 我拿走了他们拥有的东西,并对其进行了一些重新混合,使其更简单(更少的代码,并且做同样的事情)。 You need JDK 7, but you can drop these in an IDE. 您需要JDK 7,但可以将它们放在IDE中。 Hit run on Server first. 首先在服务器上运行。 Then hit run on client. 然后点击在客户端上运行。 Then click the output area of the IDE and start typing in the client. 然后单击IDE的输出区域,然后开始输入客户端。 Or you can run them from the command line. 或者,您可以从命令行运行它们。

package com.examples;
import java.net.*;
import java.io.*;

public class EchoServer {
  public static void main(String... args) throws IOException {

    int port;

    if ( args.length != 1 ) {
        System.out.println("listening to port 9999");
        port = 9999;
    } else {
        port = Integer.parseInt ( args[ 0 ] );

    }

    try (
            ServerSocket serverSocket =
                    new ServerSocket(port);
            Socket clientSocket = serverSocket.accept();
            PrintWriter out =
                    new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));
    ) {
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            out.println(inputLine);
        }
    }
  }
}

The above uses the new JDK 7 try with auto close syntax. 上面使用带有自动关闭语法的新JDK 7 try。 You want this. 你要这个。

Then here is the remixed client. 然后是重新混合的客户端。

package com.examples;

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

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

    String host;
    int port;

    if ( args.length != 2 ) {
        System.out.println("binding to port localhost:9999");
        host = "localhost";
        port = 9999;
    } else {
        host = args[ 0 ];
        port = Integer.parseInt ( args[ 1 ] );
    }

    try (
            Socket echoSocket = new Socket ( host, port );
            PrintWriter out =
                    new PrintWriter ( echoSocket.getOutputStream (), true );
            BufferedReader in =
                    new BufferedReader (
                            new InputStreamReader ( echoSocket.getInputStream () ) );
            BufferedReader stdIn =
                    new BufferedReader (
                            new InputStreamReader ( System.in ) )
    ) {
        System.out.println("Type in some text please.");
        String userInput;
        while ( ( userInput = stdIn.readLine () ) != null ) {
            out.println ( userInput );
            System.out.println ( "echo: " + in.readLine () );
        }
    }
  }
}

The server is as follows: 服务器如下:

We grab the port number from the args passed to main or just set them to 9999 if they are not passed on command line. 我们从传递给main的args中获取端口号,或者如果未在命令行上传递它们,则将它们设置为9999。

    int port;

    if ( args.length != 1 ) {
        System.out.println("listening to port 9999");
        port = 9999;
    } else {
        port = Integer.parseInt ( args[ 0 ] );

    }

Then in the try statement parens we open up our server socket streak gak 然后在try语句中,我们打开服务器套接字条码gak

            ServerSocket serverSocket =
                    new ServerSocket(port);
            Socket clientSocket = serverSocket.accept();
            PrintWriter out =
                    new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream())); 

If the above does not make sense, then you have to learn more about streams. 如果以上没有意义,那么您必须了解有关流的更多信息。 Go to the tutorial on input/output (read and writing files), then come back to this. 转到有关输入/输出(读取和写入文件)的教程,然后回到此。

Basically it is wrapping the output stream of the server socket in PrintWriter and wrapping the input stream in a BufferedReader. 基本上,它是将服务器套接字的输出流包装在PrintWriter中,并将输入流包装在BufferedReader中。 The Java I/O API is a bit daunting if you have not worked with it before so I suggest starting with the I/O tutorial a bit. 如果您以前没有使用过Java I / O API,那么它会有些令人生畏,因此,我建议您从I / O教程入手。

Here is the original: 这是原始的:
EchoClient 回声客户端
EchoServer 回声服务器

Based on where you got messed up, start reading about IO-Streams , then IO-Character Streams . 根据您的困惑,开始阅读有关IO-Streams的信息 ,然后阅读IO-Character Streams的信息

Then come back to this after a few hours of background. 然后,经过几个小时的背景,再回到这一点。

In and Out are not defined types. In和Out是未定义的类型。 Thus you get the error. 这样就得到了错误。 Change it to another defined type and it should be fine. 将其更改为另一个定义的类型,应该没问题。

Perhaps you were trying to do something like this? 也许您正在尝试做这样的事情?

PrintWriter out =
                new PrintWriter(clientSocket.getOutputStream(), true);                   
BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));

From the EchoServer.java example, I assume that In and Out should be PrintWriter and BufferedReader , respectively (or some other output and input stream objects, as In and Out are meaningless unless you wrote the objects yourself): EchoServer.java示例中,我假设InOut应该分别是PrintWriterBufferedReader (或其他一些输出和输入流对象,因为InOut没有意义,除非您自己编写对象):

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);                  
BufferedReader in = new BufferedReader(new InputStreamReader
                                      (clientSocket.getInputStream()));

If you haven't already, check out the Reading from and Writing to a Socket Tutorial . 如果还没有,请阅读读写套接字教程

What Oracle doc are you looking at? 您在看什么Oracle文档? (link please) (请链接)

Lesson: All About Sockets looks like what you should be reading. 课程:关于套接字的所有内容看起来都应该阅读。 It has the following EchoServer : 它具有以下EchoServer

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

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

    if (args.length != 1) {
        System.err.println("Usage: java EchoServer <port number>");
        System.exit(1);
    }

    int portNumber = Integer.parseInt(args[0]);

    try (
        ServerSocket serverSocket =
            new ServerSocket(Integer.parseInt(args[0]));
        Socket clientSocket = serverSocket.accept();    
        PrintWriter out =
            new PrintWriter(clientSocket.getOutputStream(), true);                  
        BufferedReader in = new BufferedReader(
            new InputStreamReader(clientSocket.getInputStream()));
    ) {
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            out.println(inputLine);
        }
    } catch (IOException e) {
        System.out.println("Exception caught when trying to listen on port "
            + portNumber + " or listening for a connection");
        System.out.println(e.getMessage());
    }
}
}

I improved the example a bit. 我对示例进行了一些改进。 EchoServer no longer terminates after first connection (it was annoying me). 首次连接后,EchoServer不再终止(这很烦我)。 I tried to use System.console(), but it would not work in my IDE so I canned it. 我尝试使用System.console(),但它在我的IDE中不起作用,因此可以将其固定。

Notice the use of Scanner (in the EchoClient) which cut down the code quite a bit and made the example much more readable. 注意使用Scanner(在EchoClient中),这大大减少了代码,并使示例更具可读性。

Client: 客户:

        try (
                Socket echoSocket = new Socket ( host, port );
                PrintWriter socketOut =
                        new PrintWriter ( echoSocket.getOutputStream (), true );
                Scanner socketIn =  new Scanner( echoSocket.getInputStream () );
                Scanner console = new Scanner(System.in);
        ) {
            System.out.println("Type in some text please.");
            while ( console.hasNextLine () ) {
                String userInput = console.nextLine ();
                socketOut.println ( userInput );
                System.out.println ( "echo: " + socketIn.nextLine () );
            }
        }

Here is a better example and I think it also answers the original question better. 这是一个更好的例子,我认为它也可以更好地回答原始问题。

Full server with while true loop: 具有while true循环的完整服务器:

package com.examples;
import java.net.*;
import java.io.*;

public class EchoServer {
    public static void main(String... args) throws IOException {

        int port;

        if ( args.length != 1 ) {
            System.out.println("listening to port 9999");
            port = 9999;
        } else {
            port = Integer.parseInt ( args[ 0 ] );

        }

        while(true) {
            try (
                    ServerSocket serverSocket =
                            new ServerSocket(port);
                    Socket clientSocket = serverSocket.accept();
                    PrintWriter out =
                            new PrintWriter(clientSocket.getOutputStream(), true);
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(clientSocket.getInputStream()));
            ) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    out.println(inputLine);
                }
            }
        }
    }
}

Notice how the main method works even if the end user (a developer learning Sockets) is running in an IDE and passing args are not convenient. 请注意,即使最终用户(学习Sockets的开发人员)在IDE中运行并且传递args都不方便,main方法的工作方式也是如此。 When I write examples, I spend a lot of time trying to simplify and amplify the topic I am covering with as little clutter as possible. 在编写示例时,我花费了大量时间来尝试简化和扩大我正在讨论的主题,并尽可能减少混乱。

Here is the client once again, notice how the code is much shorter using Scanner than BufferredReader and it is more logical (you don't have to check for null, if there are lines process them). 再次是客户端,请注意使用Scanner编写的代码比BufferredReader短得多,并且更具逻辑性(如果有行处理它们,则不必检查null)。

Full Client 全客户

package com.examples;

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


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

        String host;
        int port;

        if ( args.length != 2 ) {
            System.out.println("binding to port localhost:9999");
            host = "localhost";
            port = 9999;
        } else {
            host = args[ 0 ];
            port = Integer.parseInt ( args[ 1 ] );

        }



        try (
                Socket echoSocket = new Socket ( host, port );
                PrintWriter socketOut =
                        new PrintWriter ( echoSocket.getOutputStream (), true );
                Scanner socketIn =  new Scanner( echoSocket.getInputStream () );
                Scanner console = new Scanner(System.in);
        ) {
            System.out.println("Type in some text please.");
            while ( console.hasNextLine () ) {
                String userInput = console.nextLine ();
                socketOut.println ( userInput );
                System.out.println ( "echo: " + socketIn.nextLine () );
            }
        }


    }

}

I also renamed the variables in Client so it is more clear what they are doing. 我还在客户端中重命名了变量,以便更清楚地了解它们在做什么。 Now that I write this I realize I could do the same for the EchoServer. 现在,我写了这篇文章,我意识到我可以为EchoServer做同样的事情。

I might add a set of socket utils to Boon . 我可能会向Boon添加一组套接字实用程序。

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

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