繁体   English   中英

套接字TCP连接

[英]Socket tcp connection

我正在android studio上开发应用程序。 我正在尝试打开套接字连接。

当用户输入正确的IP地址时,一切正常,但是如果该地址不是正确的IP,则说明Socket未连接。

但是问题在于Socket没有引发catch Exception ,应用程序正在运行,现在如果用户输入正确的IP地址,则表明套接字未连接。

我的问题是,如果IP地址不是正确的IP,为什么它不会引发catch Exception ,我该如何使其工作?

这是代码

   try {
        sockettcp = new Socket(Address, Port);
    } catch (Exception e) {
        valid = false;
    }

Socket正常方式是它尝试连接到给定端口上的给定IP。

如果由于某种原因该IP不正确, Socket将不会抛出错误,而是尝试在每分钟左右(主线程或GUI线程)重新连接时“超时”。

这种构造方法的public Socket(String host, int port)引发的4个错误是:

IOException //- if an error occurs during the connection

SocketTimeoutException //- if timeout expires before connecting

IllegalBlockingModeException //- if this socket has an associated channel, and the channel is in non-blocking mode

IllegalArgumentException //- if endpoint is null or is a SocketAddress subclass not supported by this socket

要“解决”问题,可以将超时设置为您的值(此值不能超过平台默认值)

Socket sck = new Socket();
sck.connect(new InetSocketAddress(ip, port), timeout);

要“检查”您的Socket是否已连接,可以尝试以下操作:

Socket.isConnected(); //Returns the connection state of the socket.

注意:关闭套接字不会清除其连接状态,这意味着如果已关闭的套接字在关闭之前已成功连接,则此方法将对关闭的套接字返回true(请参见isClosed() )。

有关Socket更多信息,请参见javadoc

暂无
暂无

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

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