网络通信3要素
要素1:IP地址
IP地址操作类: InetAddress
package com.heima.test;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressDemo {
public static void main(String[] args) throws Exception {
InetAddress ip1 = InetAddress.getLocalHost();
System.out.println(ip1);
System.out.println(ip1.getHostName());
System.out.println(ip1.getHostAddress());
InetAddress ip2 = InetAddress.getByName("www.baidu.com");
System.out.println(ip2.getHostName());
System.out.println(ip2.getHostAddress());
InetAddress ip3 = InetAddress.getByName("119.63.197.151");
System.out.println(ip3.getHostName());
System.out.println(ip3.getHostAddress());
System.out.println(ip3.isReachable(5000));
}
}
要素2:端口号
要素3:协议
UDP通信
基础知识
package com.heima.test.TCP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ServerDemo {
public static void main(String[] args) throws Exception {
System.out.println("============服务端先启动=============");
DatagramSocket socket = new DatagramSocket(8888);
byte[] buffer = new byte[1024 * 64];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
int len = packet.getLength();
String s = new String(buffer, 0, len);
System.out.println("收到了 :" + s);
String ip = packet.getSocketAddress().toString();
System.out.println("对方的地址 :" + ip);
int port = packet.getPort();
System.out.println("对方端口 : " + port);
socket.close();
}
}
package com.heima.test.TCP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class ClientDemo {
public static void main(String[] args) throws Exception {
System.out.println("=================客户端后启动===================");
DatagramSocket socket = new DatagramSocket(6666);
byte[] buffer = "我是一个中国人".getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 8888);
socket.send(packet);
socket.close();
}
}
多发多收
package com.heima.test.TCP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class ClientDemo1 {
public static void main(String[] args) throws Exception {
System.out.println("=================客户端1后启动===================");
DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请你说 : ");
String msg = sc.nextLine();
if ("exit".equals(msg)){
System.out.println("离线成功");
socket.close();
break;
}
byte[] buffer = msg.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("192.168.0.109"), 9999);
socket.send(packet);
}
}
}
package com.heima.test.TCP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ServerDemo1 {
public static void main(String[] args) throws Exception {
System.out.println("============服务端1先启动=============");
DatagramSocket socket = new DatagramSocket(9999);
byte[] buffer = new byte[1024 * 64];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
socket.receive(packet);
int len = packet.getLength();
String s = new String(buffer, 0, len);
System.out.println("收到了来自 :" + packet.getAddress() + ",对方端口是" + packet.getPort() + "的消息 : " + s);
}
}
}
广播,组播
package com.hyway.delivergoods.test;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class UDPClientBroadcast {
public static void main(String[] args) throws Exception {
System.out.println("=========windows笔记本客户端启动=========");
DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入消息 : ");
String msg = sc.nextLine();
if ("exit".equals(msg)) {
System.out.println("离线成功");
socket.close();
return;
}
byte[] buffer = msg.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("255.255.255.255"), 9999);
socket.send(packet);
}
}
}
package com.hyway.delivergoods.test;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServerBroadcast {
public static void main(String[] args) throws Exception {
System.out.println("=============windows笔记本服务端启动==============");
DatagramSocket socket = new DatagramSocket(9999);
byte[] buffer = new byte[1024 * 8];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
socket.receive(packet);
int len = packet.getLength();
String s = new String(buffer, 0, len);
System.out.println("收到了来自mac :" + packet.getAddress() + ",对方端口是 " + packet.getPort() + "的消息 :" + s);
}
}
}
- 组播
package com.hyway.delivergoods.test;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class UDPClientGroupcast {
public static void main(String[] args) throws Exception {
System.out.println("=========windows笔记本客户端启动=========");
DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入消息 : ");
String msg = sc.nextLine();
if ("exit".equals(msg)) {
System.out.println("离线成功");
socket.close();
return;
}
byte[] buffer = msg.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("224.0.1.1"), 9999);
socket.send(packet);
}
}
}
package com.hyway.delivergoods.test;
import java.net.*;
public class UDPServerGroupcast {
public static void main(String[] args) throws Exception {
System.out.println("=============windows笔记本服务端启动==============");
MulticastSocket socket = new MulticastSocket(9999);
socket.joinGroup(new InetSocketAddress(InetAddress.getByName("224.0.1.1"),9999),
NetworkInterface.getByInetAddress(InetAddress.getLocalHost()));
byte[] buffer = new byte[1024 * 8];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
socket.receive(packet);
int len = packet.getLength();
String s = new String(buffer, 0, len);
System.out.println("收到了来自mac :" + packet.getAddress() + ",对方端口是 " + packet.getPort() + "的消息 :" + s);
}
}
}
TCP通信
基础知识-Socket套接字
package com.heima.test.TCP1;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
public class SocketClient {
public static void main(String[] args) {
try {
System.out.println("==============客户端启动成功==============");
Socket socket = new Socket("127.0.0.1", 7777);
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println("我是TCP客户端,我已经与你对接,并发出邀请:约吗?");
ps.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.heima.test.TCP1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] args) {
try {
System.out.println("==============服务端启动成功==============");
ServerSocket serverSocket = new ServerSocket(7777);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String msg;
if ((msg = br.readLine()) != null) {
System.out.println(socket.getRemoteSocketAddress() + "远程地址说了 : " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
多发多收消息
package com.heima.test.TCP1;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class MultiSocketClient {
public static void main(String[] args) {
try {
System.out.println("==============客户端启动成功==============");
Socket socket = new Socket("127.0.0.1", 7777);
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请说 : ");
String msg = sc.nextLine();
ps.println(msg);
ps.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.heima.test.TCP1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiSocketServer {
public static void main(String[] args) {
try {
System.out.println("==============服务端启动成功==============");
ServerSocket serverSocket = new ServerSocket(7777);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String msg;
while ((msg = br.readLine()) != null) {
System.out.println(socket.getRemoteSocketAddress() + "远程地址说了 : " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
同时接受多个客户端消息(重点)
package com.heima.test.TCP1;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadSocketClient {
public static void main(String[] args) {
try {
System.out.println("==============客户端启动成功==============");
Socket socket = new Socket("127.0.0.1", 7777);
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请说 : ");
String msg = sc.nextLine();
ps.println(msg);
ps.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.heima.test.TCP1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ThreadSocketServer {
public static void main(String[] args) {
try {
System.out.println("==============服务端启动成功==============");
ServerSocket serverSocket = new ServerSocket(7777);
while (true) {
Socket socket = serverSocket.accept();
System.out.println(socket.getRemoteSocketAddress()+" 上线了!");
new ServerReaderThread(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.heima.test.TCP1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class ServerReaderThread extends Thread {
private Socket socket;
public ServerReaderThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String msg;
while ((msg = br.readLine()) != null) {
System.out.println(socket.getRemoteSocketAddress() + " 远程地址说了 : " + msg);
}
} catch (Exception e) {
System.out.println(socket.getRemoteSocketAddress() + " 离开了!!!");
}
}
}
使用线程池优化
package com.heima.test.TCP1;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadSocketClient {
public static void main(String[] args) {
try {
System.out.println("==============客户端启动成功==============");
Socket socket = new Socket("127.0.0.1", 6666);
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请说 : ");
String msg = sc.nextLine();
ps.println(msg);
ps.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.heima.test.TCP1;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;
public class ThreadSocketServer {
private static ExecutorService pool = new ThreadPoolExecutor(3, 5, 6,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(2),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) {
try {
System.out.println("==============服务端启动成功==============");
ServerSocket serverSocket = new ServerSocket(6666);
while (true) {
Socket socket = serverSocket.accept();
System.out.println(socket.getRemoteSocketAddress() + " 上线了!");
Runnable target = new ServerReaderRunnable(socket);
pool.execute(target);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.heima.test.TCP1;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class ServerReaderRunnable implements Runnable {
private Socket socket;
public ServerReaderRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String msg;
while ((msg = br.readLine()) != null) {
System.out.println(socket.getRemoteSocketAddress() + " 远程地址说了 : " + msg);
}
} catch (Exception e) {
System.out.println(socket.getRemoteSocketAddress() + " 离开了!!!");
}
}
}
实战案例 - 即时通信
package com.heima.test.TCP2;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ClientMSG {
public static void main(String[] args) {
try {
System.out.println("==============客户端启动成功==============");
Socket socket = new Socket("127.0.0.1", 6666);
new ClientReaderThread(socket).start();
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请说 : ");
String msg = sc.nextLine();
ps.println(msg);
ps.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ClientReaderThread extends Thread {
private Socket socket;
public ClientReaderThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String msg;
while ((msg = br.readLine()) != null) {
System.out.println(" 收到了消息 : " + msg);
}
} catch (Exception e) {
System.out.println("服务端把你踢出去了。。。");
}
}
}
package com.heima.test.TCP2;
import com.heima.test.TCP1.ServerReaderRunnable;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ServerMSG {
public static List<Socket> allOnlineSocket = new ArrayList<>();
public static void main(String[] args) {
try {
System.out.println("==============服务端启动成功==============");
ServerSocket serverSocket = new ServerSocket(6666);
while (true) {
Socket socket = serverSocket.accept();
System.out.println(socket.getRemoteSocketAddress() + " 上线了!");
allOnlineSocket.add(socket);
new ServerReaderThread(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerReaderThread extends Thread {
private Socket socket;
public ServerReaderThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String msg;
while ((msg = br.readLine()) != null) {
System.out.println(socket.getRemoteSocketAddress() + " 发来了 : " + msg);
sendMsgToAll(msg);
}
} catch (Exception e) {
System.out.println(socket.getRemoteSocketAddress() + " 离开了!!!");
ServerMSG.allOnlineSocket.remove(socket);
}
}
private void sendMsgToAll(String msg) throws Exception {
for (Socket socket : ServerMSG.allOnlineSocket) {
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println(msg);
ps.flush();
}
}
}
实战案例 - 模拟BS系统
package com.heima.test.TCP3;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class BSserver {
public static void main(String[] args) {
try {
System.out.println("==============服务端启动成功==============");
ServerSocket ss = new ServerSocket(8080);
while (true) {
Socket socket = ss.accept();
new ServerReaderThread(socket).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ServerReaderThread extends Thread {
private Socket socket;
public ServerReaderThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("HTTP/1.1 200 OK");
ps.println("Content-Type:text/html;charset=UTF-8");
ps.println();
ps.println("我是响应信息");
ps.close();
} catch (Exception e) {
System.out.println(socket.getRemoteSocketAddress() + " 离开了!!!");
}
}
}
package com.heima.test.TCP3;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;
public class BSserver {
private static ExecutorService pool = new ThreadPoolExecutor(3, 5, 6,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(2),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) {
try {
System.out.println("==============服务端启动成功==============");
ServerSocket ss = new ServerSocket(8080);
while (true) {
Socket socket = ss.accept();
pool.execute(new ServerReaderRunnable(socket));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ServerReaderRunnable implements Runnable {
private Socket socket;
public ServerReaderRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("HTTP/1.1 200 OK");
ps.println("Content-Type:text/html;charset=UTF-8");
ps.println();
ps.println("我是响应信息2");
ps.close();
} catch (Exception e) {
System.out.println(socket.getRemoteSocketAddress() + " 离开了!!!");
}
}
}