网络编程

来源:互联网 发布:数据存储加密解决方案 编辑:程序博客网 时间:2024/06/06 00:04

面向应用层的类:
URL
URLConnection
面向传输层的类:
TCP协议相关类:Socket、ServerSocket
UDP协议相关类:DatagramPacket、DatagramSocket、MulticastSocket
面向网络层的类
表示IP 地址的类: InetAddress

获取InetAddrss对象方法
public static InetAddress getByName(String host)
host:主机地址的域名或IP地址。
public static InetAddress getLocalHost() 获取本地主机ip地址。
InetAddress常用方法
public String getHostAddress():获得本对象的IP地址
public String getHostName(): 获得本对象的主机名。

Socket通信程序基本结构都一样,包括以下四个基本步骤:

1、在客户方和服务器方创建Socket/ServerSocket实例。
2、打开连接到Socket的输入/输出流。
3、利用输入/输出流,按照一定的协议对Socket进行读/写操作。
4、关闭输入/输出流和Socket。
通常,程序员的主要工作是针对所要完成的功能在第3步进行编程,第1、2、4步对所有的通信程序来说几乎都是一样的。

TCP编程

public class TCPClient {    public static void main(String[] args) {        try {            // 新建TCP的socket            Socket socket = new Socket("192.168.1.183", 20000);            // 获取输出流            OutputStream os = socket.getOutputStream();            // 发送数据            os.write("你好漂亮".getBytes());            // 获取输入流            InputStream is = socket.getInputStream();            // 读取数据            byte[] buf = new byte[1024];            int li = is.read(buf);            // 输出读取的数据            System.out.println(new String(buf, 0, li));            socket.close();        } catch (Exception e) {            e.printStackTrace();        }    }}
public class TCPServer {     public static void main(String[] args){         try {             //新建TCP的服务器Socket            ServerSocket server=new ServerSocket(20000);            //ServerSocket等待连接            Socket socket=server.accept();            //获取连接的IP地址            String ip=socket.getInetAddress().getHostAddress();            System.out.println(ip+"...connection");            //获取输入流            InputStream is=socket.getInputStream();;            byte[] buf=new byte[1024];            //接收数据            int len=is.read(buf);            System.out.println(new String(buf,0,len));            //获取输出流            OutputStream os=socket.getOutputStream();            //发送数据            os.write("谢谢你".getBytes());            socket.close();            server.close();        } catch (IOException e) {            e.printStackTrace();        }     }}

UDP编程

public class UDPClient {    public static void main(String[] args) {        DatagramSocket socket = null;        Scanner sc = new Scanner(System.in);        try {// UDP的Socket            socket = new DatagramSocket();            System.out.println("请开始聊天:");            String date = sc.nextLine();            while (!"bye".equals(date)) {                // 要发送的数据                byte[] buf = date.getBytes();                // 创建UDP数据包                DatagramPacket dp = new DatagramPacket(buf, buf.length,                        InetAddress.getByName("192.168.1.183"), 10000);                // 发送数据                socket.send(dp);                date = sc.nextLine();            }        } catch (Exception e) {            e.printStackTrace();        } finally {            sc.close();            socket.close();        }    }}
public class UDPServer {    public static void main(String[] args) {        try {            // UDP的Socket            DatagramSocket socket = new DatagramSocket(10000);            // 存放要接收的数据的缓冲区            byte[] buf = new byte[1024];            // 新建UDP的数据包            DatagramPacket dp = new DatagramPacket(buf, buf.length);            while (true) {                // 接收UDP的数据                socket.receive(dp);// 阻塞                // 将从Socket获取的数据变成字符串                String data = new String(dp.getData(), 0, dp.getLength());                // 输出获取的字符串                InetAddress ip = dp.getAddress();                System.out.println(ip.getHostAddress() + "/"                        + ip.getHostAddress() + "say:" + data);            }        } catch (Exception e) {            e.printStackTrace();        }    }}

URL

public class URLDemo {    public static void main(String[] args){        String addr="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2835357568,2173739438&fm=116&gp=0.jpg";        FileOutputStream fos=null;        InputStream in=null;        try {            URL url=new URL(addr);//url表示要操作的远程资源            fos=new FileOutputStream("D:\\test.jpg");            in=url.openStream();//打开输入流            //读取远程资源,并通过输出流输出到本地文件中去            byte[] buf=new byte[1024];            int size=0;            while((size=in.read(buf))!=-1){                fos.write(buf, 0, size);            }            fos.flush();        } catch (Exception e) {            e.printStackTrace();        }finally{       //关闭输入流            if(in!=null)            try {                in.close();            } catch (IOException e) {                e.printStackTrace();            }            //关闭输出流            if(fos!=null){                try {                    fos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}

参考博客:http://blog.sina.com.cn/s/blog_6213b4e50100je4g.html