本文共 3118 字,大约阅读时间需要 10 分钟。
代码示例:
流 程:
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 url = new URL("“http://localhost:8080/examples/beauty.jpg?username=Tom”");
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/