Java 网络编程
完整代码:https://github.com/JiaZhengJingXianSheng/Java-Study-Notes/tree/main/Java-%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B
测试IP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public class TestInetAddress { public static void main(String[] args) { try { InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1"); System.out.println(inetAddress1); InetAddress inetAddress2 = InetAddress.getByName("localhost"); System.out.println(inetAddress2); InetAddress inetAddress3 = InetAddress.getLocalHost(); System.out.println(inetAddress3);
InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com"); System.out.println(inetAddress4);
System.out.println(inetAddress1.getCanonicalHostName()); System.out.println(inetAddress1.getHostAddress()); System.out.println(inetAddress1.getHostName());
} catch (UnknownHostException e) { e.printStackTrace(); } } }
|
端口
1 2 3
| netstat -ano #查看所有端口 netstat -ano|findstr "5900" #查看指定端口 tasklist|find "8689" #查看指定端口的进程
|
1 2 3 4 5 6 7 8 9 10 11 12
| public class TestInetSocketAddress { public static void main(String[] args) { InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080); InetSocketAddress socketAddress2 = new InetSocketAddress("localhost",8080); System.out.println(socketAddress); System.out.println(socketAddress2);
System.out.println(socketAddress.getAddress()); System.out.println(socketAddress.getHostName()); System.out.println(socketAddress.getPort()); } }
|
通信协议
OSI 协议
七层划分为:应用层、表示层、会话层、传输层、网络层、数据链路层、物理层。
五层划分为:应用层、传输层、网络层、数据链路层、物理层。
TCP/IP协议簇
重要:
出名的协议:
TCP UDP对比
TCP面向连接 (三次握手)
UDP面向无连接
TCP 实现
客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public class TcpClientDemo01 { public static void main(String[] args) { Socket socket = null; OutputStream os = null; try { InetAddress serverIp = InetAddress.getByName("127.0.0.1"); int port = 9999; socket = new Socket(serverIp,port); os = socket.getOutputStream(); os.write("hello,world".getBytes());
} catch (Exception e) { e.printStackTrace(); }finally { if (socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
|
服务端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| public class TcpServerDemo01 { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos = null; try { serverSocket = new ServerSocket(9999); while(true){ socket = serverSocket.accept(); is = socket.getInputStream();
baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } System.out.println(baos.toString()); }
} catch (IOException e) { e.printStackTrace(); } finally { if (baos != null) { try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
|
TCP 实现文件上传
客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class TcpClientDemo02 { public static void main(String[] args) throws Exception { Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("头像.jpg"));
byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer))!=-1){ os.write(buffer,0,len); }
socket.shutdownOutput();
InputStream is = socket.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer2 = new byte[1024]; int len2; while((len2 = is.read(buffer2))!=-1){ baos.write(buffer2,0,len2); } System.out.println(baos.toString()); baos.close(); fis.close(); os.close(); socket.close();
} }
|
服务端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class TcpServerDemo02 { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(9000); Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("receive.jpg")); byte[] buffer = new byte[1024]; int len; while((len=is.read(buffer))!=-1){ fos.write(buffer,0,len); }
OutputStream os = socket.getOutputStream(); os.write("server接收完毕".getBytes());
fos.close(); is.close(); socket.close(); serverSocket.close(); } }
|
Tomcat
服务端
客户端
UDP 消息发送
发送端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public class UdpClientDemo01 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket();
String msg = "你好啊,服务器!"; InetAddress localhost = InetAddress.getLocalHost(); int port = 9090; DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.getBytes().length, localhost, port);
socket.send(packet);
socket.close();
} }
|
接收端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class UdpServerDemo01 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet); System.out.println(new String(packet.getData())); socket.close(); } }
|
UDP 实现聊天
接收端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public class UdpReceiveDemo01 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(6666);
while (true){ byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container,container.length);
socket.receive(packet);
byte[] data = packet.getData(); String receiveData = new String(data, 0, data.length);
System.out.println(receiveData); if(receiveData.trim().equals("bye")){ break; }
} } }
|
发送端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class UdpSenderDemo01 { public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true){ String data = reader.readLine();
DatagramPacket packet = new DatagramPacket(data.getBytes(),data.getBytes().length, new InetSocketAddress("localhost",6666));
socket.send(packet); if (data.equals("bye")){ break; } }
socket.close(); } }
|
在线咨询
双方都可收发
发送类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| public class TalkSend implements Runnable{ private DatagramSocket socket; private BufferedReader reader;
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 { this.socket = new DatagramSocket(this.fromPort);
} catch (SocketException e) { e.printStackTrace(); System.out.println("socket 创建错误!"); } }
@Override public void run() {
while(true){ reader = new BufferedReader(new InputStreamReader(System.in)); String data = null; try { data = reader.readLine(); } catch (IOException e) { e.printStackTrace(); }
DatagramPacket packet = new DatagramPacket(data.getBytes(),data.getBytes().length, new InetSocketAddress(this.toIP ,this.toPort));
try { socket.send(packet); } catch (IOException e) { e.printStackTrace(); } if (data.equals("bye")){ break; } }
socket.close(); } }
|
接受类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| public class TalkReceive implements Runnable{ private DatagramSocket socket; private int port; private String msgFrom;
public TalkReceive(int port, String msgFrom) { this.msgFrom = msgFrom; this.port = port; try { this.socket = new DatagramSocket(this.port); } catch (SocketException e) { e.printStackTrace(); System.out.println("socket 创建错误!"); } }
@Override public void run() {
while (true){ try { byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container,container.length);
socket.receive(packet);
byte[] data = packet.getData(); String receiveData = new String(data, 0, data.length);
System.out.println(msgFrom + ": "+ receiveData); if(receiveData.trim().equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } socket.close(); } }
|
开启聊天线程
启动聊天
1 2 3 4 5 6 7
| public class TalkTeacher { public static void main(String[] args) { new Thread(new TalkSend(5555,"localhost",6666)).start(); new Thread(new TalkReceive(8888,"学生")).start();
} }
|
1 2 3 4 5 6 7 8
| public class TalkStudent { public static void main(String[] args) { new Thread(new TalkSend(7777,"localhost",8888)).start(); new Thread(new TalkReceive(6666,"老师")).start();
} }
|
URL
统一资源定位符:定位互联网上某一个资源。
DNS:域名解析
协议 : // ip地址 : 端口 / 项目名 / 资源
1 2 3 4 5 6 7 8 9 10 11 12
| public class URLDemo01 { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=test&password=123"); System.out.println(url.getProtocol()); System.out.println(url.getHost()); System.out.println(url.getPort()); System.out.println(url.getPath()); System.out.println(url.getFile()); System.out.println(url.getQuery()); } }
|
URL 下载资源
将URL的路径换成网络资源链接,就可以下载网络资源。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class URLDownloads { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:8080/lyz/SecurityFile.txt"); URLConnection urlConnection = (HttpURLConnection)url.openConnection(); InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("SecurityFile.txt"); byte[] buffer = new byte[1024]; int len; while((len = inputStream.read(buffer))!=-1){ fos.write(buffer,0,len); } fos.close(); inputStream.close(); } }
|