Socket网络编程基本介绍和实例

网络编程基本介绍

InetAddress (IP)

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP地址测试
 */
public class TestInetAddress {

    public static void main(String[] args) throws UnknownHostException {
        // 获得本机 IP
        InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
        InetAddress inetAddress2 = InetAddress.getByName("localhost");
        InetAddress inetAddress3 = InetAddress.getLocalHost();
        System.out.println(inetAddress1);
        System.out.println(inetAddress2);
        System.out.println(inetAddress3);

        // 获得网络 IP
        InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
        System.out.println(inetAddress4);
    }
}

控制台输出:
/127.0.0.1
localhost/127.0.0.1
DESKTOP-OHMG1V7/192.168.254.1
www.baidu.com/182.61.200.7

Process finished with exit code 0

InetSocketAddress(端口)

public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 3306);
        
        System.out.println(socketAddress.getAddress());
        System.out.println(socketAddress.getHostName());
        System.out.println(socketAddress.getHostString());
        System.out.println(socketAddress.getPort());

    }
}

控制台输出:
/127.0.0.1
127.0.0.1
127.0.0.1
3306

Process finished with exit code 0

基于TCP的文件下载

客户端

package lesson02;

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

public class TCPClientDemo1 {

    public static void main(String[] args) throws Exception {
        // 创建一个 Socket
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
        // 获得一个输出流
        OutputStream outputStream = socket.getOutputStream();
        // 读取本地文件
        FileInputStream fileInputStream = new FileInputStream(new File("12.jpg"));
        // 写出去
        byte[] bytes = new byte[1024];
        int len;
        while((len = fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
        }
        //关闭资源
        fileInputStream.close();
        outputStream.close();
        socket.close();

    }
}

服务器

package lesson02;

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

public class TCPServerDemo01 {

    public static void main(String[] args) throws IOException {
        // 创建一个 ServerSocket,Socket服务器
        ServerSocket serverSocket = new ServerSocket(8888);
        // 接收到服务器传来的Socket
        Socket socket = serverSocket.accept();
        // 获得输入流
        InputStream inputStream = socket.getInputStream();
        // 写到本地
        byte[] bytes = new byte[1024];
        int len;
        FileOutputStream fileOutputStream = new FileOutputStream(new File("45.jpg"));
        while ((len = inputStream.read(bytes)) != -1){
            fileOutputStream.write(bytes,0,len);
        }
        fileOutputStream.close();
        inputStream.close();
        socket.close();
    }

}

基于UDP的数据报通信

发送者

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
// 发送者
public class TestUDPChatUser1 {
    public static void main(String[] args) throws Exception {
		// 声明一个数据报Socket
        DatagramSocket datagramSocket = new DatagramSocket(9999);

        String message = "Hello World!";
		// 声明一个数据报包(byte[],起始,结束,InetAddress,port)
        DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(),0,
                                                           message.getBytes().length, InetAddress.getByName("127.0.0.1"),8888);
        // 发送出去
        datagramSocket.send(datagramPacket);
    }
}

接收者

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

public class TestUDPChatUser2 {
    public static void main(String[] args) throws Exception {
		// 声明一个数据报 Socket
        DatagramSocket datagramSocket = new DatagramSocket(8888);
		// 接收的缓冲区数据
        byte[] bytes = new byte[1024];
		// 声明一个数据报包
        DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,InetAddress.getByName("127.0.0.1"),9999);\
        // 接收
        datagramSocket.receive(datagramPacket);

        System.out.println("从 " + datagramPacket.getAddress() +" 端口 "+ datagramPacket.getPort() + " 收到了 :");
        System.out.println(new String(datagramPacket.getData()));
    }
}

​ 输出

从 /127.0.0.1 端口 9999 收到了 :
Hello World!                                                                                  
Process finished with exit code 0

URL下载网络资源

URL基本介绍

import java.net.URL;

public class TestURL {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://dss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin_zoom/12.jpg?2");
        System.out.println(url.getPort());
        System.out.println(url.getProtocol());
        System.out.println(url.getHost());
        System.out.println(url.getFile());
    }
}

控制台输出:
-1
https
dss1.bdstatic.com
/kvoZeXSm1A5BphGlnYG/skin_zoom/12.jpg?2

Process finished with exit code 0

URL下载网络资源

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class TestURLDownLoad {

    public static void main(String[] args) throws Exception {
        // 声明一个URL连接
        URL url = new URL("https://dss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin_zoom/12.jpg?2");
        // 这个URL是根据HTTP协议的,可以得到HTTP连接
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        // IO基本操作开始
        InputStream inputStream = httpURLConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(new File("12.jpg"));

        byte[] bytes = new byte[1024];
        int len;
        while((len = inputStream.read(bytes)) != -1){
            fileOutputStream.write(bytes,0,len);
        }

        fileOutputStream.close();
        inputStream.close();
        httpURLConnection.disconnect();

    }
}

总结

​ 不管是文件还是字符串还是什么数据,其实都可以通过流进行传输。
​ 可以选择基于UDP传输,也可以选择基于TCP传输
​ 想要实现不同的功能,只需要自己处理流数据就好了
​ 例如:从控制台获取字符串,发送,实现聊天功能等

代码

GitHub地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值