您的位置:首页 > 科技 > 能源 > Day25

Day25

2024/10/5 23:30:54 来源:https://blog.csdn.net/m0_67496588/article/details/139271466  浏览:    关键词:Day25

Day25

网络编程概念

计算机网络

网络编程:TCP协议的三次握手四次挥手

IP地址,端口号:取值范围:065535,保留端口号:01024。

网络协议:TCP协议(类比于打电话,双方需要连接),UDP协议(类比于发短信),Http协议

IP地址

知识点:InetAddress - 主机类

public static void main(String[] args) throws UnknownHostException {//获取本机的InetAddress对象InetAddress localHost = InetAddress.getLocalHost();System.out.println(localHost);System.out.println("------------");//获取服务器地址InetAddress byName = InetAddress.getByName("www.baidu.com");System.out.println(byName);System.out.println("------------");//获取服务器地址//注意:一个域名可以指向多个服务器InetAddress[] allByName = InetAddress.getAllByName("www.baidu.com");for (InetAddress inetAddress : allByName) {System.out.println(inetAddress);}}

网络协议

Socket:

Scoket也叫套接字,其表示的是IP地址和端口号的组合。

网络编程主要就是指Socket编程,网络间的通信其实就是Socket间的通信,数据就通过IO流在两个Scoket间进行传递。

TCP协议

知识点:InetAddress - 主机类:

public static void main(String[] args) throws UnknownHostException {//获取本机的InetAddress对象InetAddress localHost = InetAddress.getLocalHost();System.out.println(localHost);System.out.println("------------");//获取服务器地址InetAddress byName = InetAddress.getByName("www.baidu.com");System.out.println(byName);System.out.println("------------");//获取服务器地址//注意:一个域名可以指向多个服务器InetAddress[] allByName = InetAddress.getAllByName("www.baidu.com");for (InetAddress inetAddress : allByName) {System.out.println(inetAddress);}}

客户端与服务端:

//服务端
public class Server {public static void main(String[] args) throws IOException {//注意:关闭流等同于关闭Socket//大唐经理ServerSocket server = new ServerSocket(8080);//18号技师Socket socket = server.accept();//2.接受来自客户端的数据BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));String readLine = br.readLine();System.out.println(readLine);//3.向客户端发送数据PrintStream ps = new PrintStream(socket.getOutputStream());ps.println("18号:刚满18岁~~~");br.close();ps.close();server.close();}
//客户端
public class Client {public static void main(String[] args) throws UnknownHostException, IOException {//注意:关闭流等同于关闭Socket//小康Socket socket = new Socket("127.0.0.1",8080);//1.向服务端发送数据PrintStream ps = new PrintStream(socket.getOutputStream());ps.println("小康:小妹妹你多大了...");//4.接受来自服务端的数据BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));String readLine;readLine = br.readLine();System.out.println(readLine);ps.close();br.close();socket.close();}

知识点:TCP案例 – 传输文件

public class Server {public static void main(String[] args) throws IOException {ServerSocket server = new ServerSocket(8080);Socket socket = server.accept();BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.mp4"));byte[] bs = new byte[1024];int len;while((len=bis.read(bs))!=-1){bos.write(bs,0,len);}bis.close();bos.close();server.close();}public class Client {/*** 知识点:TCP案例 -- 传输文件*/public static void main(String[] args) throws UnknownHostException, IOException {Socket socket = new Socket("127.0.0.1",8080);BufferedInputStream bis = new BufferedInputStream(new FileInputStream("copy.mp4"));BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());int len;byte[] bs=new byte[1024];while((len=bis.read(bs))!=-1){bos.write(bs,0,len);}bis.close();bos.close();socket.close();}

知识点:TCP案例 - 一对一聊天

public class Server {@SuppressWarnings("all")public static void main(String[] args) throws IOException {ServerSocket server = new ServerSocket(8080);Socket socket = server.accept();new ReceiveThread(socket).start();PrintStream ps = new PrintStream(socket.getOutputStream());Scanner scan = new Scanner(System.in);while(true){ps.println("18号技师:" + scan.next());}}
}public class Client {/*** 知识点:TCP案例 - 优化一对一聊天*/@SuppressWarnings("all")public static void main(String[] args) throws UnknownHostException, IOException {Socket socket = new Socket("127.0.0.1", 8080);new ReceiveThread(socket).start();PrintStream ps = new PrintStream(socket.getOutputStream());Scanner scan = new Scanner(System.in);while(true){ps.println("小康:" + scan.next());}}
}//接受消息的线程
public class ReceiveThread extends Thread{private Socket socket;public ReceiveThread(Socket socket) {this.socket = socket;}@Overridepublic void run() {BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}String readLine;boolean bool = true;while(bool){try {readLine = br.readLine();System.out.println(readLine);}catch(SocketException e){bool = false;}catch (IOException e) {e.printStackTrace();}}}}

知识点:TCP案例 - 群聊

public class Client {/*** 知识点:TCP案例 - 群聊*/@SuppressWarnings("all")public static void main(String[] args) throws UnknownHostException, IOException {Socket socket = new Socket("127.0.0.1", 8080);new ReceiveThread(socket).start();PrintStream ps = new PrintStream(socket.getOutputStream());Scanner scan = new Scanner(System.in);while(true){ps.println("小康:" + scan.next());}}public class Server {public static ConcurrentHashMap<String, PrintStream> map = new ConcurrentHashMap<>();@SuppressWarnings("all")public static void main(String[] args) throws IOException {ServerSocket server = new ServerSocket(8080);while(true){Socket socket = server.accept();new ServerThread(socket).start();String ip = socket.getInetAddress().toString();PrintStream ps = new PrintStream(socket.getOutputStream());map.put(ip, ps);}}
}//接受消息的线程
public class ReceiveThread extends Thread{private Socket socket;public ReceiveThread(Socket socket) {this.socket = socket;}@Overridepublic void run() {BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));} catch (UnsupportedEncodingException e1) {e1.printStackTrace();} catch (IOException e1) {e1.printStackTrace();}boolean bool = true;while(bool){String readLine;try {readLine = br.readLine();System.out.println(readLine);} catch (SocketException e) {bool = false;} catch (IOException e) {e.printStackTrace();} }}}public class ServerThread extends Thread{private Socket socket;public ServerThread(Socket socket) {this.socket = socket;}@Overridepublic void run() {//接受当前Socket的消息,并发送给其他Sockettry {BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));while(true){String readLine = br.readLine();System.out.println(readLine);ConcurrentHashMap<String,PrintStream> map = Server.map;Set<Entry<String,PrintStream>> entrySet = map.entrySet();for (Entry<String, PrintStream> entry : entrySet) {String ip = entry.getKey();PrintStream ps = entry.getValue();if(!socket.getInetAddress().toString().equals(ip)){ps.println(readLine);}}}} catch (IOException e) {e.printStackTrace();}}
}

UDP协议

public class ReceiveThread extends Thread{private DatagramSocket socket;public ReceiveThread(DatagramSocket socket) {this.socket = socket;}@Overridepublic void run() {while(true){byte[] buf = new byte[1024];DatagramPacket p = new DatagramPacket(buf , buf.length);try {socket.receive(p);//socket.receive(p) 方法会阻塞当前线程,直到从网络上接收到一个数据报文。} catch (IOException e) {e.printStackTrace();}System.out.println(new String(buf).trim());}}
}public class SendThread extends Thread{private DatagramSocket socket;private String ip;private int port;private String nickName;public SendThread(DatagramSocket socket, String ip, int port, String nickName) {this.socket = socket;this.ip = ip;this.port = port;this.nickName = nickName;}@Overridepublic void run() {Scanner scan = new Scanner(System.in);while(true){byte[] buf = (nickName + ":" + scan.next()).getBytes();DatagramPacket p;try {p = new DatagramPacket(buf, 0, buf.length, InetAddress.getByName(ip), port);socket.send(p);//发送数据报包} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}}public class Client01 {public static void main(String[] args) throws SocketException {//7070表示当前端口的端口号DatagramSocket socket = new DatagramSocket(7070);new SendThread(socket, "127.0.0.1", 8080, "小蒲").start();new ReceiveThread(socket).start();}
}public class Client02 {public static void main(String[] args) throws SocketException {//8080表示当前端口的端口号DatagramSocket socket = new DatagramSocket(8080);new SendThread(socket, "127.0.0.1", 7070, "小康").start();new ReceiveThread(socket).start();}
}

TCP VS UDP (学习后自行比对)

TCP UDP

是否连接 面向连接 无面向连接

传输可靠性 可靠 不可靠

应用场合 传输大量数据 少量数据

速度 慢 快

HTTP协议

知识点:http - 操作淘宝接口

public static void main(String[] args) throws IOException {//创建链接对象URL url = new URL("https://suggest.taobao.com/sug?code=gbk&q=始祖鸟&callback=cb");//获取链接对象HttpURLConnection connection = (HttpURLConnection) url.openConnection();//设置参数connection.setConnectTimeout(5000);//设置连接超时时间connection.setReadTimeout(5000);//设置读取超时时间connection.setDoInput(true);//设置允许使用输入流connection.setDoOutput(true);//设置允许使用输出流//获取响应状态码int responseCode = connection.getResponseCode();if(responseCode == HttpURLConnection.HTTP_OK){//获取响应中的数据BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));char[] cs = new char[1024];int len;while((len = br.read(cs)) != -1){System.out.println(new String(cs, 0, len));}br.close();}else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND){System.out.println("响应错误,页面未找到");}}

知识点:http - 下载图片

public static void main(String[] args) throws IOException {//创建链接对象URL url = new URL("https://img2.baidu.com/it/u=2245838154,3561436125&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=750");//获取链接对象HttpURLConnection connection = (HttpURLConnection) url.openConnection();//设置参数connection.setConnectTimeout(5000);//设置连接超时时间connection.setReadTimeout(5000);//设置读取超时时间connection.setDoInput(true);//设置允许使用输入流connection.setDoOutput(true);//设置允许使用输出流//获取响应状态码int responseCode = connection.getResponseCode();if(responseCode == HttpURLConnection.HTTP_OK){//获取响应中的数据BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("许凯.jpg"));byte[] bs = new byte[1024];int len;while((len=bis.read(bs)) != -1){bos.write(bs, 0, len);}bis.close();bos.close();}else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND){System.out.println("响应错误,页面未找到");}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com