- 网络变成概述
- 编写的应用程序可以与网络上其他设备中的应用程序进行数据交互。
- CS架构:Client/Server
- BS架构:Browser-Server
- 网络变成三要素
- IP:表示设备在网络中的地址,是网络中设备的唯一标识
- 端口:应用程序在设备中唯一的标识
- 协议:连接和数据在网络中传输的规则
- 协议
- UDP协议:无连接,不可靠,通信效率高
- TCP协议:面向连接,可靠通信
- 三次握手:
- 四次挥手
- UDP代码–多发多收
public class Client {
public static void main(String[] args) throws Exception {
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[] bytes = msg.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length
, InetAddress.getLocalHost(), 6666);
socket.send(packet);
}
}
}
public class Server {
public static void main(String[] args) throws Exception {
System.out.println("----服务端启动----");
DatagramSocket socket = new DatagramSocket(6666);
byte[] buffer = new byte[1024 * 64];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
socket.receive(packet);
int len = packet.getLength();
String rs = new String(buffer, 0 , len);
System.out.println(rs);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(packet.getPort());
System.out.println("--------------------------------------");
}
}
}
- TCP代码–多发多收
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 8888);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请说:");
String msg = sc.nextLine();
if("exit".equals(msg)){
System.out.println("欢迎您下次光临!退出成功!");
dos.close();
socket.close();
break;
}
dos.writeUTF(msg);
dos.flush();
}
}
}
public class Server {
public static void main(String[] args) throws Exception {
System.out.println("-----服务端启动成功-------");
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
while (true) {
try {
String rs = dis.readUTF();
System.out.println(rs);
} catch (Exception e) {
System.out.println(socket.getRemoteSocketAddress() + "离线了!");
dis.close();
socket.close();
break;
}
}
}
}