网络编程demo之Udp和URL

首先是udp编程客户端发送消息给服务端,服务端接受然后打印到console控制台上

下面是一个有代表性的demo

package com.henu.liulei;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.junit.Test;

public class TestUdp {
@Test
public void send()
{
try {
DatagramSocket ds=new DatagramSocket();//创建一个datagramsocket对象
byte[]b;
b="你好,我是要发送的数据".getBytes();
//创建一个数据报,每个数据报不能大于64k,都记录着数据信息,发送端的IP,端口号,以及要发送的接收端的ip,端口号
DatagramPacket pack=new DatagramPacket(b,0,b.length,InetAddress.getByName("127.0.0.1"),9090);
ds.send(pack);//socket对象把数据发送出去
ds.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void receive()
{
try {
DatagramSocket ds=new DatagramSocket(9090);//也是先创建一个socket对象,只需要指明端口号就

//以
byte []b=new byte[1024];
DatagramPacket pack=new DatagramPacket(b,0,b.length);//声明数据报
ds.receive(pack);//接受数据报
String str =new String(pack.getData(),0,pack.getLength());//把数据报里面的内容转为字符串打印出来
System.out.println(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

下面是url编程的demo

package com.henu.liulei;

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

//Url:统一资源定位符,一个URL对象对应互联网上一个资源
//我们可以通过URL的对象调用其相应的方法,将此资源读取下载
public class TestUrl {
public static void main(String[] args) throws Exception {
//创建一个url的对象
URL url=new URL("http://www.baidu.com/index.html");//相当于File file=new File("文件的路径")
//
System.out.println(url.getHost());//主机
System.out.println(url.getProtocol());//协议
System.out.println(url.getPort());//端口号
System.out.println(url.getFile());//文件名
System.out.println(url.getRef());//获取url在文件里的相对位置
System.out.println(url.getQuery());//获取该url的查询名
//将服务端的资源读进来
InputStream is=url.openStream();
byte []b=new byte[20];
int len;
while((len = is.read(b))!= -1) {
String str=new String(b,0,len);
System.out.println(str);
}
is.close();
//如果既有数据的输入,又有数据的输出则考虑URLConnection
URLConnection urlCon=url.openConnection();
InputStream is1=urlCon.getInputStream();
FileOutputStream fos=new FileOutputStream(new File("abc.txt"));
byte []b1=new byte[10];
int len1;
while((len1=is1.read(b1))!=-1) {
fos.write(b1,0,len1);
}
fos.close();
is1.close();



}
}

posted @ 2018-07-18 20:36  你的雷哥  阅读(187)  评论(0编辑  收藏  举报