Socket 入门一 连接主机

本文介绍了Socket编程的基础概念及异常处理机制,包括Socket连接、超时设置、常见异常类型及其对应解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、代码
package com.socket;


import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;


public class SoketDemo {
public static void main(String[] args) {
String[] a = new String[2];
a[0] = "www.javathinker.org";
a[1] = "80";
String host = "localhost";
int port = 25;
if (a[0].length() > 0) {
host = a[0];
port = Integer.parseInt(a[1]);
}
new SoketDemo().conncet(host, port);


}


public void conncet(String host, int port) {
SocketAddress remoterAddr = new InetSocketAddress(host, port);
Socket socket = null;
String result = null;
try {
long begin = System.currentTimeMillis();
socket = new Socket();
socket.connect(remoterAddr, 1000);// 超时设置时间


long end = System.currentTimeMillis();
result = (end - begin) + "ms";
}


catch (BindException e) {
result = "local address and port can't be binded";
} catch (UnknownHostException e) {
result = "Unknown exception";
} catch (ConnectException e) {
result = "Connection Exception";
} catch (SocketTimeoutException e) {
result = "timeout";
} catch (IOException e) {
result = "failure";
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(remoterAddr + ":" + result);
}
}

}

2、输出结果截图


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值