网络编程
如何定位到网络上的一台主机
tcp
稳定
三次握手
最少需要三次四次挥手
二次确认
UDP
- 不连接不稳定
- 不考虑接收者的情况
- DDOS
TCP实现聊天
package com.example.demo.utils;
import org.apache.catalina.connector.OutputBuffer;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
//接收
public class ScoketDemo {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader read = null;
try {
//创建socket服务
int port = 9999;
serverSocket = new ServerSocket(port);
while(true) {
//接受连接,形成传输通道
socket = serverSocket.accept();
//从socket写到内存中,对于内存是输入所以是输入流
read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(read.readLine());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(read != null) {
try {
read.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();
}
}
}
}
}
//发送
class client{
public static void main(String[] args) {
Socket socket = null;
PrintWriter writer = null;
try {
//连接到socket服务器
socket = new Socket("127.0.0.1", 9999);
//写数据到socket
writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
UDP实现消息发送
class UdpClient {
public static void main(String[] args) throws IOException {
//创建socket
DatagramSocket socket = new DatagramSocket();
//创建数据包
DatagramPacket packet = new DatagramPacket("msg".getBytes(), 0, "msg".getBytes().length, InetAddress.getByName("localhost"), 9999);
//发送数据包
socket.send(packet);
}
}
class UdpServer {
public static void main(String[] args) throws IOException {
//开放端口
DatagramSocket server = new DatagramSocket(9999);
//定义数据包
DatagramPacket datagramPacket = new DatagramPacket(new byte[1024],0,new byte[1024].length);
//阻塞接受
server.receive(datagramPacket);
System.out.println(datagramPacket.getAddress().getHostAddress());
System.out.println(datagramPacket.getData());
}
}
使用udp实现连天功能
发送者
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class UdpSender {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9998);
while(true) {
Scanner sc = new Scanner(System.in);
String msg = sc.nextLine();
InetAddress inetAddress = InetAddress.getByName("localhost");
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.length(), inetAddress, 9999);
socket.send(datagramPacket);
}
}
}