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();
}
}
}
}