Java-网络编程-TCP+UDP-02

Java网络编程

IP:InetAddress

  • 唯一定位一台网络上计算机
  • 127.0.0.1:本地localhost
  • IP地址分类:
    • IPv4/IPv6
    • 公网-私网
  • ipconfig查询本机IP
  • 域名:记忆IP问题

public class Main {
    public static void main(String[] args) {
        try {
            //查询本机IP地址
            InetAddress m1=InetAddress.getByName("127.0.0.1");
            InetAddress m2=InetAddress.getByName("localhost");
            InetAddress m3=InetAddress.getLocalHost();
            System.out.println(m1);
            System.out.println(m2);
            System.out.println(m3);

            //查询网站IP地址
            InetAddress a1=InetAddress.getByName("www.baidu.com");
            System.out.println(a1);

            //常用方法
            System.out.println(a1.getAddress());
            System.out.println(a1.getCanonicalHostName());  //IP
            System.out.println(a1.getHostAddress());        //IP
            System.out.println(a1.getHostName());           //域名
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

端口Port:InetSocketAddress

-InetSocketAddress类主要作用是封装端口 他是在在InetAddress基础上加端口

public class test {
	public static void main(String[] args) {
		InetSocketAddress socketAddress=new InetSocketAddress("127.0.0.1",8080);
		System.out.println(socketAddress);
		System.out.println(socketAddress.getHostName());
		System.out.println(socketAddress.getPort());
	}
}

端口表示计算机上的一个程序的进程

  • 不同的进程有不同的端口号。
  • 被规定0-65535

端口分类

  • 公有端口:0-1023
    • HTTP:80
    • HTTPS:443
    • FTP:21
    • Telent:23
  • 程序注册端口:1024-49151,分配用户或程序。
    • Tomcat:8080
    • MySQL:3306
    • Oracle:1521
  • 动态、私有端口:49152-65535

DOS命令:

netstat -ano #查看所有端口
netstat -ano|findstr "8080" #查看指定进程
tasklist|findstr "8696" #查看指定端口进程

TCP实现聊天

  1. 客户端:连接服务器Socket----发送消息
public class TCClient {
	public static void main(String[] args) {
		InetAddress serverIP=null;
		Socket socket=null;
		OutputStream os=null;
		try {
			//服务器地址
			serverIP=InetAddress.getByName("127.0.0.1");
			//端口
			int port=999;
			//建立Socket连接
			socket=new Socket(serverIP,port);
			//发送消息
			os=socket.getOutputStream();
			os.write("hello".getBytes());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//关闭源
			try {
				os.close();
				socket.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
	}
}
  1. 服务端:建立服务端口ServerSocket----等待用户连接accept----接收消息

public class TCPServer {
	public static void main(String[] args) {
		ServerSocket serverSocket=null;
		Socket socket=null;
		InputStream is=null;
		ByteArrayOutputStream baos=null;
		try {
			//设置接收端口
			serverSocket=new ServerSocket(999);
			while(true) {
				//等待连接
				socket=serverSocket.accept();
				//读取客户端消息
				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 (Exception e) {
			// TODO: handle exception
		}finally {
			//关闭源
			try {
				baos.close();
				is.close();
				socket.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
}

TCP上传文件

public class TCPServer {
	public static void main(String[] args) throws Exception {
		//创建服务
		ServerSocket serverSocket=new ServerSocket(9029);
		//监听客户端连接
		Socket socket=serverSocket.accept();
		//获取输入流
		InputStream is=socket.getInputStream();
		//文件输出流
		FileOutputStream fos=new FileOutputStream(new File("001Copy.jpg"));
		byte[] buffer=new byte[1024];
		int len;
		while((len=is.read())!=-1) {
			fos.write(buffer,0,len);
		}
		
		//通知客户端接收完毕
		OutputStream os=socket.getOutputStream();
		os.write("I am Finish".getBytes());
		//关闭资源
		fos.close();
		is.close();
		socket.close();
		serverSocket.close();
	}
}
public class TCClient {
	public static void main(String[] args) throws Exception {
		//建立连接
		Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9029);
		//创建输出流
		OutputStream os=socket.getOutputStream();
		//读取文件
		FileInputStream file=new FileInputStream(new File("001.jpg"));
		//写出文件
		byte[] buffer=new byte[1024];
		int len;
		while((len=file.read(buffer))!=-1) {
			os.write(buffer,0,len);
		}
		//通知服务器我已经接收完了
		socket.shutdownOutput();
		//确定服务器接收
		InputStream is=socket.getInputStream();
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		byte[] buffer2=new byte[1024];
		int len2;
		while((len2=is.read(buffer2))!=-1) {
			bos.write(buffer2,0,len2);
		}
		System.out.println(bos.toString());
		//关闭源
		bos.close();
		file.close();
		os.close();
		socket.close();
	}
}

Tomcat

服务端

  • Tomcat服务器 S

客户端

  • 浏览器 B

网站

UDP-发送消息

-发送端

public class UDPClient {
	public static void main(String[] args) throws Exception {
		//建立Socket
		DatagramSocket socket = new DatagramSocket(); 
		//建立包
		String msg="hello UDP";
		//发送给谁
		InetAddress local=InetAddress.getByName("127.0.0.1");
		int port=9090;
		DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,local,port);
		//发送包
		socket.send(packet);
		//关闭
		socket.close();
	}
  • 接收端

public class UDPServer {
	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(new String(packet.getData(),0,packet.getLength()));
		//关闭资源
		socket.close();
	}
}

UDP-多线程聊天

  1. 发送线程
public class sendMassage implements Runnable{
    DatagramSocket socket=null;
    BufferedReader reader=null;
    private int toPort;
    private String toIP;
    private int fromPort;
    //构造函数

    public sendMassage(int toPort, String toIP, int fromPort) {
        this.toPort = toPort;
        this.toIP = toIP;
        this.fromPort = fromPort;
        try {
            this.socket=new DatagramSocket(fromPort);
            reader=new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true){
            try {
                //读取信息
                String data=reader.readLine();
                //获得字节流
                byte[] datas=data.getBytes();
                //打包
                DatagramPacket packet=new DatagramPacket(datas,0,datas.length,new InetSocketAddress(toIP,toPort));
                //发送
                socket.send(packet);
                if(data.equals("bye"))
                    break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

  1. 接收线程

public class ReciveMassage implements Runnable{
    DatagramSocket socket=null;
    private int port;
    private String name;

    public ReciveMassage(int port,String name) {
        this.port = port;
        this.name = name;
        try {
            socket=new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true){
            try {
                //准备接收包裹
                byte[] datas = new byte[1024];
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length);
                //接收
                socket.receive(packet);
                //断开连接
                byte[] data=packet.getData();
                String recive=new String(data,0,data.length);
                System.out.println(this.name+":"+recive);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
  1. 建立用户
public class Student1 {
    public static void main(String[] args) {
        new Thread(new sendMassage(777,"127.0.0.1",999)).start();
        new Thread(new ReciveMassage(888,"学生2:")).start();
    }
}

public class student2 {
    public static void main(String[] args) {
        new Thread(new sendMassage(888,"127.0.0.1",555)).start();
        new Thread(new ReciveMassage(777,"学生2:")).start();
    }
}

UDP下载网络资源

  • URL:同意资源定位符:定位资源,定义互联网上的某一资源
  • DNS域名解析:把域名对应从IP地址
协议://ip地址:端口/项目名/资源

public class URLtest {
    public static void main(String[] args) {
        try {
            //下载地址
            URL url = new URL("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2325607797,558634102&fm=26&gp=0.jpg");
            //建立连接
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            //获得输入流
            InputStream in = connection.getInputStream();
            //建立输出流
            FileOutputStream os=new FileOutputStream("001.jpg");
            //下载
            byte[]buffer=new byte[1024];
            int len;
            while((len=in.read(buffer))!=-1){
                os.write(buffer,0,len);
            }
            //关闭资源
            os.close();
            in.close();
            connection.disconnect();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值