一、查询个人主机的IP地址与Internet上WWW服务器的IP地址
Internet上主机的地址有两种表示方式,即域名和IP地址,通常使用InetAddress类的一些常用方法可直接获取,不过InetAddress类无构造方法,因此不能使用new运算符创建该类对象,通常使用它提供的静态方法获得。而static方法通常会产生UnknownHostException 异常,因此程序中也需捕获异常。
public static void main(String[] args) {
try {
/*查询本机地址 */
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1"); //127.0.0.1是个人主机的IP地址
System.out.println(inetAddress1);
InetAddress inetAddress11 = InetAddress.getByName("localhost"); //可以用主机名代替IP地址
System.out.println(inetAddress11);
InetAddress inetAddress12 = InetAddress.getLocalHost();
System.out.println(inetAddress12);
//查询网站IP的地址
InetAddress inetAddress2 = InetAddress.getByName("www.tomcat.com");
System.out.println(inetAddress12);
/* 常用方法 */
System.out.println(inetAddress2.getHostAddress());
System.out.println("规范自己的名字:" + inetAddress2.getCanonicalHostName());
System.out.println("IP:" + inetAddress2.getHostAddress());
System.out.println("域名/个人电脑的名字:" + inetAddress1.getHostName());
}
catch (UnknownHostException e)
{
e.printStackTrace(); //可以不用写该内容
}
}
二、使用URL类访问网络资源
可通过URL直接读取网络上服务器中的文件内容。一般分为三个步骤:一是创建URL类对象;二是利用URL类的openStream()方法获得对应的InputStream类的对象;三是通过InputStream对象来读取文件内容。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class URLfile {
public static void main(String[] args) {
//本例访问网易云音乐的网页板块
String urlName = "https://music.163.com/#/discover/playlist";
if(args.length >0) urlName = args[0];
new URLfile().display(urlName);
}
public void display(String urlName)
{
try {
URL url1 = new URL(urlName); //创建URL类对象url1;
InputStreamReader in = new InputStreamReader(url1.openStream());
BufferedReader br = new BufferedReader(in);
String aLine;
while ((aLine = br.readLine()) != null)
System.out.println(aLine);
}
catch (MalformedURLException murle) //创建URL对象时,若发生错误,系统会发生该异常,为非运行时异常需捕获处理
{
System.out.println(murle);
}
catch (IOException ioe) //该异常类是在非运行时最常用的异常类,所有输入输出相关命令的情况都必须处理IOException所引发的异常
{
System.out.println(ioe);
}
}
}
三、TCP/IP下的Socket网路通信
Socket通信的步骤:
- 在服务器端创建一个ServerSocket对象,并指定端口号;
- 运行ServerSocket的accept()方法,等候客户请求;
- 客户端创建一个Socket对象,指定服务器的IP地址和端口号,向服务器端发出连
接请求; - 服务器端接收到客户端请求后,创建Socket对象与客户端建立连接;
- 服务器端和客户端分别建立输人输出数据流,进行数据传输;
- 通信结束后,服务器端和客户端分别关闭相应的Socket连接;
- 服务器端程序运行结束后,调用ServerSocket对象的Close()方法停止等候客户端
请求。
注:下例代码中服务器端只建立了输入流,客户端仅建立了输出流。
服务器端的程序代码如下:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1.服务端的地址
serverSocket = new ServerSocket(9999);
//2.等待客户端连接过来
socket = serverSocket.accept();
//3.读取客户端的消息
is = socket.getInputStream();
// 管道流
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
}
catch (IOException e)
{
e.printStackTrace();
}finally {
//关闭资源
if(baos != null){
try{
baos.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
if(is != null)
{
try {
is.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
if(socket != null)
{
try {
socket.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
if(serverSocket != null)
{
try {
serverSocket.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
}
}
客户端程序代码如下:
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo {
public static void main(String[] args) {
OutputStream os = null;
Socket socket = null;
try {
//1.要知道服务器的地址、端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999; //端口号
//2.建立一个socket连接
socket = new Socket(serverIP,port);
//3.发送消息 IO流
os = socket.getOutputStream();
os.write("hello,welcom to learn java".getBytes());
}
catch (Exception e)
{
e.printStackTrace();
}finally {
if (os != null){
try{
os.close();
}catch (IOException e)
{
e.printStackTrace();
}
}
if (socket != null){
try{
socket.close();
}catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
UDP无连接的数据报通信
数据包通信的基本模式:客户端将数据打包,形成数据包,然后将其发往目的地;服务器端接收客户端发来的数据包,查看其内容。
Java中用于无连接的数据包通信有DatagramSocket和DatagramPacket两类。DatagramPacket类用于在发送端将待发送的数据打包,在接收端将收到的数据拆包;DatagramSocket类用于实现数据报通信的过程中的数据包的发送与接收
客户端代码如下:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClientDemo {
public static void main(String[] args) throws Exception {
//1.建立一个UDP Socket对象
DatagramSocket socket = new DatagramSocket();
//2.建个包
String msg = "hello Serverdemo!";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
//3.数据打包
DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length ,localhost,port); //数据/数据的长度起始/要发送给谁
//3.发送包
socket.send(packet);
//4.关闭流
socket.close();
}
}
服务器端代码如下:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServerDemo {
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket socket = new DatagramSocket(9090); //捕获异常
//接收数据包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
//输出数据包内容
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(), 0, packet.getLength()));
//关闭连接
socket.close();
}
}
注:两种通信模式的代码仅只是表达了其基本模式的程序代码,还有许多可补充之处,该代码仅供参考。