Java网络编程详解

Posted xianya

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java网络编程详解相关的知识,希望对你有一定的参考价值。

1.  InetAddress类

     InetAddress用来代表IP地址。一个InetAdress的对象就代表着一个IP地址,

  • getByName(String host)如何创建InetAddress的对象
  • getHostName(): 获取IP地址对应的域名,
  • getHostAddress():获取IP地址
package com.yyx.test;

import java.net.InetAddress;

public class TestInetAddress {
    public static void main(String[] args) {
        InetAddress inetAddress = null;
        InetAddress iAddress=null;
        try {
            inetAddress = InetAddress.getByName("www.jtxgps.com");
            System.out.println(inetAddress);
            System.out.println(inetAddress.getHostAddress());
            System.out.println(inetAddress.getHostName());
            
            System.out.println("=============================");
            iAddress=InetAddress.getLocalHost();
            System.out.println(iAddress);
            System.out.println(iAddress.getHostAddress());
            System.out.println(iAddress.getHostName());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

2.  Socket套接字

     TCP协议

实例一:客户端发送信息给服务器,服务器接收信息,并返回接收成功

     客户端

package com.yyx.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientSocket {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            // 创建一个Socket的对象,通过构造器指明服务端的IP地址,以及其接收程序的端口号
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
            // getOutputStream():发送数据,方法返回OutputStream的对象
            outputStream = socket.getOutputStream();
            String info = "我是客户端,请多关照";
            outputStream.write(info.getBytes());
            // shutdownOutput():执行此方法,显式的告诉服务端发送完毕!
            socket.shutdownOutput();

            inputStream = socket.getInputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) != -1) {
                String str = new String(b, 0, len);
                System.out.print(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭相应的流和Socket对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

     服务器端

package com.yyx.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerSocket {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // 创建一个ServerSocket的对象,通过构造器指明自身的端口号
            serverSocket = new ServerSocket(9090);
            // 服务端监听 调用其accept()方法,返回一个Socket的对象
            socket = serverSocket.accept();
            inputStream = socket.getInputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) != -1) {
                String str = new String(b, 0, len);
                System.out.println(str);
            }
            System.out.println("收到来自于" + socket.getInetAddress().getHostAddress() + "客户端的连接");

            String strInfo = "服务器已收到信息";
            outputStream = socket.getOutputStream();
            outputStream.write(strInfo.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭相应的流以及Socket、ServerSocket的对象
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.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();
                }
            }
        }

    }
}

实例二:客户端发送文件给服务器,服务器接收文件并保存,并返回接收成功

      客户端

package com.yyx.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientSocket {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        FileInputStream fileInputStream=null;
        try {
            // 创建一个Socket的对象,通过构造器指明服务端的IP地址,以及其接收程序的端口号
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
            
            String pathname = "F:" + File.separator + "source.jpg";
            File file = new File(pathname);
            fileInputStream=new FileInputStream(file);
            
            // getOutputStream():发送数据,方法返回OutputStream的对象
            outputStream = socket.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = fileInputStream.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
            
            // shutdownOutput():执行此方法,显式的告诉服务端发送完毕!
            socket.shutdownOutput();

            inputStream = socket.getInputStream();
            byte[] bAnother = new byte[1024];
            int lenAnother;
            while ((lenAnother = inputStream.read(bAnother)) != -1) {
                String str = new String(bAnother, 0, lenAnother);
                System.out.print(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭相应的流和Socket对象,从后往前关闭
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

     服务器端

package com.yyx.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerSocket {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            // 创建一个ServerSocket的对象,通过构造器指明自身的端口号
            serverSocket = new ServerSocket(9090);
            // 服务端监听 调用其accept()方法,返回一个Socket的对象
            socket = serverSocket.accept();
            inputStream = socket.getInputStream();

            String pathname = "F:" + File.separator + "target.jpg";
            File file = new File(pathname);
            fileOutputStream = new FileOutputStream(file);

            /*
             * 接收客户端发送文件,并保存到本地文件
             */
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) != -1) {
                fileOutputStream.write(b, 0, len);
            }

            String strInfo = "你发送的图片我已接收成功!";
            outputStream = socket.getOutputStream();
            outputStream.write(strInfo.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭相应的流以及Socket、ServerSocket的对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if (inputStream != null) {
                try {
                    inputStream.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();
                }
            }
        }

    }
}

     UDP协议

     客户端

package com.yyx.test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpClientSocket {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket();
            String str = "你好,我是要发送的数据";
            byte[] b = str.getBytes();

            /*
             * 创建一个数据报:每一个数据报不能大于64k,都记录着数据信息,发送端的IP、端口号,以及要发送到 的接收端的IP、端口号
             */
            DatagramPacket pack = new DatagramPacket(b, 0, b.length, InetAddress.getByName("127.0.0.1"), 9090);

            datagramSocket.send(pack);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (datagramSocket != null) {
                datagramSocket.close();

            }
        }
    }
}

     服务器端

package com.yyx.test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpServerSocket {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(9090);
            byte[] b = new byte[1024];
            DatagramPacket pack = new DatagramPacket(b, 0, b.length);
            datagramSocket.receive(pack);

            String str = new String(pack.getData(), 0, pack.getLength());
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (datagramSocket != null) {
                datagramSocket.close();

            }
        }
    }
}

3.  URL编程  

package com.yyx.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class UrlConnection {
    public static void main(String[] args) {
        URL url = null;
        URLConnection urlConn = null;
        InputStream is = null;
        InputStream inputStream = null;
        try {
            url = new URL("http://www.cnblogs.com");
            inputStream = url.openStream();

            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) != -1) {
                String str = new String(b, 0, len);
                System.out.print(str);
            }

            // 如果既有数据的输入,又有数据的输出,则考虑使用URLConnection
            urlConn = url.openConnection();
            is = urlConn.getInputStream();
            FileOutputStream fos = new FileOutputStream(new File("abc.txt"));
            byte[] bAnother = new byte[20];
            int lenAnother;
            while ((lenAnother = is.read(bAnother)) != -1) {
                fos.write(bAnother, 0, lenAnother);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

以上是关于Java网络编程详解的主要内容,如果未能解决你的问题,请参考以下文章

Java线程池详解

Java 线程池详解

Java线程池详解

详解Android WebView加载html片段

Java调用SQL Server的存储过程详解(转)

java并发编程synchronized详解