import java.net.InetAddress;
import java.io.IOException;
class Main {
public static void main(String[] args) {
try {
InetAddress localAddress = InetAddress.getLocalHost();
//获得本地主机
InetAddress remoteAddress =
InetAddress.getByName("www.itcast.cn");//由主机名获得IP地址
System.out.println("本机主机名"+localAddress.getHostName()+
"本机IP地址: " + localAddress.getHostAddress() +
",www.itcast.cn的IP地址: " + remoteAddress.getHostAddress()
+ ",3秒是否可以到达主机名为www.itcast的IP地址: " +
remoteAddress.isReachable(3000));
} catch (IOException e) {
e.printStackTrace();
}
}
}
URL编程
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try {
URL url=new URL(https://www.baidu.com");// 注意URL地址需要包含协议部分
InputStream input = url.openStream(); // 注意正确的方法为openStream(),
//openStream()方法会抛出IOException,类型为InputStream
Scanner scan = new Scanner(input);//实例化Scanner对象
scan.useDelimiter("\n");//读取分隔符
while (scan.hasNext()) {
System.out.println(scan.next());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
如下所示,读取了网页HTML文件。将其复制然后加到新建的HTML文档,运行可见网页。
TCP通信
ServerSocket服务器端,用于连接客户端请求。
Socket客户端,向服务器发出连接请求。
1对1的TCP通信
服务器端程序
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
Socket client = null;
OutputStream os = null;//输出流对象声明
try {
ServerSocket serverSocket = new ServerSocket(7788);//创建端口号为7788的SerSocket对象
System.out.println("等待建立连接");
client = serverSocket.accept();//服务端等待客户端连接
os = client.getOutputStream();//获得客户端输出流
System.out.println("开始连接");
os.write("北京欢迎你".getBytes());//使用输出流输出数据
Thread.sleep(5000);//线程休眠一段时间
System.out.println("结束通信");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
class Main{
public static void main(String[] args) throws Exception{
Socket client = null;//声明客户端对象
BufferedReader buf = null;//声明BufferedReadered对象,用于接收信息
try {
client = new Socket("BF-201911291316",7788);//以指定主机名与端口号创建对象
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));//创建一个BufferedReader对象用于接收客户端输入流信息
String str = buf.readLine();//读取该信息
System.out.println("服务器输出内容:" + str);//输出
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (buf != null) {
buf.close();//关闭输入流
}
if (client != null) {
client.close();//关闭Socket对象
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
执行程序时,先启动服务器端,再启动客户端
多线程TCP网络程序
服务器端允许多个客户端程序同时访问
(1)TCPClient客户端程序1
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws Exception{
Socket client = null;
BufferedReader buf = null;
try {
client = new Socket("BF-201911291316",7798);//客户端指派主机名和端口号
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = buf.readLine();
System.out.println("服务器输出内容:" + str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (buf != null) {
buf.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(2)Client客户端程序2
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception{
Socket client = null;
BufferedReader buf = null;
try {
client = new Socket("BF-201911291316",7798);
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = buf.readLine();
System.out.println("服务器输出内容:" + str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (buf != null) {
buf.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
TCPserver服务端程序
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(7798)) {
while (true) {
Socket client;
try {
client = serverSocket.accept();
int port = client.getPort();
System.out.println("与端口号为" + port + "的客户端连接成功");
new Thread(() -> {
try (OutputStream os = client.getOutputStream()) {
System.out.println("开始交换数据");
os.write("北京欢迎你".getBytes());
Thread.sleep(5000);
System.out.println("交换数据结束");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (client != null && !client.isClosed()) {
client.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
依次启动三个程序,可以看到两个客户端与服务器端交互情况。
UDP通信
(1)DatagramPacket类,即数据报对象,包含数据以及数据报长度,IP地址和端口号等信息。接收端用一个字符数组作为参数存储接收的信息,发送端不但要存放发送信息的字符数组,还要指明端口号和IP地址。
(2)DatagramSocket类,用于发送主机中建立数据报通信方式。
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Receiver {
public static void main(String[] args) {
try {
byte[] buffer = new byte[1024];
DatagramSocket ds = new DatagramSocket(8954);
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
System.out.println("等待接收数据");
try{
ds.receive(dp);}
catch(IOException e){
System.out.println(e);
}
String S = new String(dp.getData(), 0, dp.getLength()) + "from" + dp.getAddress().getHostAddress() + ":"
+ dp.getPort();
System.out.println(S);
ds.close();
}
catch ( SocketException e) {
e.printStackTrace();
}
}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Sender {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(3000);
String S = "hello world";
byte[] b = S.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, InetAddress.getByName("BF-201911291316"), 8954);
System.out.println("发送信息");
ds.send(dp);
ds.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
多线程UDP网络程序
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class TT{
public static void main(String[] args) {
new Receive().start();
new Send().start();
}
}
class Receive extends Thread{
public void run(){
try {
DatagramSocket socket=new DatagramSocket(6666);
DatagramPacket packet=new DatagramPacket(new byte[1024], 1024);
while(true){
socket.receive(packet);
byte[] arr=packet.getData();
int len=packet.getLength();
String ip=packet.getAddress().getHostAddress();
System.out.println(ip+":"+new String(arr,0,len));
}
}catch(IOException e){
e.printStackTrace();
}
}
}
class Send extends Thread{
public void run(){
try {
DatagramSocket socket=new DatagramSocket();
Scanner sc=new Scanner(System.in);
while(true){
String ip=sc.nextLine();
if("quiet".equals(ip)){
break;
}
DatagramPacket packet=new DatagramPacket(ip.getBytes(),ip.getBytes().length, InetAddress.getByName("BF-201911291316"),6666);
socket.send(packet);
socket.close();
}
}catch (IOException e
){
System.out.println(e);
}
}
}