简单的Java套接字客户端,引发此ConnectException的原因是什么? [英] Simple java socket client, what throws this ConnectException?

查看:210
本文介绍了简单的Java套接字客户端,引发此ConnectException的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为非常简单的服务器编写一个非常简单的客户端.如果服务器未运行,则第17行在运行时引发ConnectException,我不知道为什么.我已经查看了有关Socket的构造函数和getInputStream()的文档,但没有一个抛出ConnectException.我查看了CE的文档,并说:有信号表明尝试将套接字连接到远程地址和端口时发生错误.通常,该连接被远程拒绝(例如,没有进程正在侦听远程地址/港口)."没错,服务器没有运行,但是除了试错之外,我不知道该怎么办,为什么在Socket文档中不显示它?

I'm writing a very simple client for my very simple server. Line 17 throws a ConnectException at runtime if the server isn't running, I don't know why. I have looked through the docs for Socket's constructor and getInputStream(), but neither of them throw the ConnectException. I looked at the docs for the CE, and it says "Signals that an error occurred while attempting to connect a socket to a remote address and port. Typically, the connection was refused remotely (e.g., no process is listening on the remote address/port)." That is exactly true, the server isn't running, but I don't know how to know this other than trial and error, why isn't it in the docs for Socket?

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

public class ClientLesson {

    //declare vars
    static Socket socket;
    static BufferedReader inputReader;

    public static void main(String[] args) throws IOException {
        try {
            socket = new Socket("Lithium", 55555);
        } catch (IOException ioe) {
            System.out.println(ioe.toString());
        }
        try {
   this is the problem --> inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException ioe) {
            System.out.print("couldn't get I/O stream");
            ioe.printStackTrace();
        }  
        String fromServer;
        while ((fromServer = inputReader.readLine()) != null) {
            System.out.println(fromServer);
        }
        inputReader.close();
        socket.close();

    }
}

推荐答案

我刚刚意识到问题是完全不同的... ConnectException由Socket构造函数抛出,并作为IOException处理,因为CE是子类型,因此现在对我来说很有意义.我在第17行得到了NPE,但是我对终端输出感到困惑,这里是:

I just realized the problem is entirely different...the ConnectException is thrown by the Socket constructor, and handled as an IOException, since CE is a subtype, that makes sense to me now. I'm getting a NPE at line 17, but I was confused by the terminal output, here it is:

nexus@Lithium ~/Desktop/Java Workspace/networking $ java ClientLesson 
java.net.ConnectException: Connection refused
Exception in thread "main" java.lang.NullPointerException
    at ClientLesson.main(ClientLesson.java:17)

我不明白这两个是分开的问题.现在我知道了问题所在,第17行应该在调用套接字上的方法之前检查一下第一次尝试是否成功.

I didn't understand those two were separate issues. Now I know the problem is line 17 should check to see if the first try was successful before calling methods on the socket.

这篇关于简单的Java套接字客户端,引发此ConnectException的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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