网络编程自学笔记 (3)

Send:

public class TalkSend implements Runnable{ DatagramSocket socket = null; BufferedReader reader = null; private int fromPort; private String toIP; private int toPort; public TalkSend(int fromPort,String toIP,int toPort ) { this.fromPort= fromPort; this.toIP = toIP; this.toPort = toPort; try{ socket=new DatagramSocket(fromPort); reader=new BufferedReader(new InputStreamReader(System.in)); }catch(Exception 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(this.toIP, this.toPort)); socket.send(packet); if (data.equals("bye")) { break; } }catch(Exception e){ e.printStackTrace(); } } socket.close(); } }

3、简单案例的实现:师生对话交流

Student:

public class TalkStudent { public static void main(String[] args) { //开启两个线程 new Thread(new TalkSend(777,"localhost",9999)).start(); new Thread(new TalkReceive(8888,"老师")).start(); } }

Teacher:

public class TalkTeacher { public static void main(String[] args) { new Thread(new TalkSend(5555,"localhost",8888)).start(); new Thread(new TalkReceive(9999,"学生")).start(); } } 1.8、URL下载网络资源

URL的组成:协议://IP地址:端口号/项目名/资源名

URLDown.java

public class URLDown { public static void main(String[] args) throws Exception { //1、下载地址 URL url = new URL("http://m701.music.126.net/20210324121008/fa40047aca19fe4a2639d56aa8b652b2/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/5546003493/cfbc/699a/fadc/6b094e5431dfc70cb57527f51db8dd4c.mp3"); //2、连接到这个服务器 HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); FileOutputStream fos = new FileOutputStream("错位时空.mp3"); byte[] buffer = new byte[1024]; int len; while ((len=inputStream.read(buffer))!=-1){ fos.write(buffer,0, len);//写出这个数据 } fos.close(); inputStream.close(); urlConnection.disconnect(); } } public class URLDemo { public static void main(String[] args) throws MalformedURLException { URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuang&passwoed=123"); System.out.println(url.getProtocol());//协议 System.out.println(url.getHost());//主机IP System.out.println(url.getPort());//端口 System.out.println(url.getPath());//全路径 System.out.println(url.getFile());//文件 System.out.println(url.getQuery());//参数 } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzpgxf.html