博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UDP网络编程和URL编程
阅读量:3964 次
发布时间:2019-05-24

本文共 3118 字,大约阅读时间需要 10 分钟。

UDP网络通信

代码示例:

流 程:

  • 1.DatagramSocket与DatagramPacket
  • 2.建立发送端,接收端
  • 3.建立数据包
  • 4.调用Socket的发送、接收方法
  • 5.关闭Socket
    发送端与接收端是两个独立的运行程序
    */
public class UDPTest {
//发送端 @Test public void sender(){
DatagramSocket socket = null; try {
socket = new DatagramSocket();// public DatagramPacket(byte[] buf,int length,InetAddress address,int port)构造数据报包,// 用来将长度为 length 的包发送到指定主机上的指定端口号。length 参数必须小于等于 buf.length String str = "我是UDP方式发送的导弹"; byte[] buffer = str.getBytes(); InetAddress inet = InetAddress.getLocalHost(); DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length,inet,7788); socket.send(packet); System.out.println("发送成功!"); } catch (IOException e) {
e.printStackTrace(); } finally {
if(socket != null){
socket.close(); } } } //接收端 @Test public void receiver(){
DatagramSocket socket = null; try {
socket = new DatagramSocket(7788); byte[] buffer = new byte[100]; DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length); socket.receive(packet); System.out.println(new String(packet.getData(),0,packet.getLength())); } catch (IOException e) {
e.printStackTrace(); } finally {
if(socket != null){
socket.close(); } } }}

URL编程

1.URL(Uniform Resource Locator)的理解:

  • URL网络编程
  • 1.URL:统一资源定位符,对应着互联网的某一资源地址
    在这里插入图片描述

2.URL的5个基本结构:

  • 2.格式:
  • http://localhost:8080/examples/beauty.jpg?username=Tom
  • 协议 主机名 端口号 资源地址 参数列表
  • 在这里插入图片描述

3.如何实例化:

URL url = new URL("“http://localhost:8080/examples/beauty.jpg?username=Tom”");

在这里插入图片描述

4.常用方法:

在这里插入图片描述

5.可以读取、下载对应的url资源:

public class URLTest1 {
public static void main(String[] args) {
HttpURLConnection urlConnection = null; InputStream is = null; FileOutputStream fos = null; try {
URL url = new URL("http://localhost:8080/examples/beauty.jpg"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); is = urlConnection.getInputStream(); fos = new FileOutputStream("day10\\beauty3.jpg"); byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len); } System.out.println("下载完成"); } catch (IOException e) {
e.printStackTrace(); } finally {
//关闭资源 if(is != null){
try {
is.close(); } catch (IOException e) {
e.printStackTrace(); } } if(fos != null){
try {
fos.close(); } catch (IOException e) {
e.printStackTrace(); } } if(urlConnection != null){
urlConnection.disconnect(); } } }}

转载地址:http://mvuki.baihongyu.com/

你可能感兴趣的文章
Python 注释
查看>>
Python 变量
查看>>
Python 数据类型 -- 数字
查看>>
Spring 管理对象
查看>>
Spring 自定义对象初始化及销毁
查看>>
Spring Batch 环境设置
查看>>
字符组转译序列
查看>>
字符转译序列
查看>>
Java 数据类型
查看>>
UTF-16 编码简介
查看>>
Java 变量名
查看>>
Java 四舍五入运算
查看>>
Spring Batch 例子: 运行系统命令
查看>>
括号及后向引用
查看>>
Spring Batch 核心概念
查看>>
Spring Batch 例子: 导入定长文件到数据库
查看>>
正则表达式
查看>>
Java I/O
查看>>
序列化
查看>>
Perl 精萃
查看>>