网络编程UDP通信
初始计算机网络基本概念
ip地址:InetAdderss
唯一定位一台网络上计算机
127.0.0.1 本机loocahost
IP地址的分类
ipv4/ipv6
ipv4 4个字节组成 32位
ipv6 128位 16进制保持
公网(互联网)/私网(局域网)
ABCD类网
A:1.0.0.1-127.255.255.255
B: 128.0.0.0-191.255.255.255
C: 192.0.0.0-223.255.255.255
D: 224.0.0.0-239.255.255.255
192.168.xxx.xxx 专门给内部组织使用
域名:记忆ip问题
ip地址类
//测试ip
public class TestInetAddress {
public static void main(String[] args) {
try {
//查询本机地址
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress1);
InetAddress inetAddress3 = InetAddress.getByName("localhost");
System.out.println(inetAddress3);
InetAddress inetAddress4 = InetAddress.getLocalHost();
System.out.println(inetAddress4);
//查询网站ip地址
InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress2);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
端口
表示计算机上的一个程序的进程
不同的进程有不同的端口号!用来区分软件的!
被规定0~65535
TCP,UDP 65535*2 单个协议下,端口号不能冲突,不同协议可以
端口分类
公有端口 0~1023
HTTP:80
HTTPS:443
FTP:21
Telent:23
程序注册端口:分配1024~4915,分配用户或者程序
Tomcat :8080
MySQL:3306
Oracle:1512
动态,私有 :49152~65535 尽量不要用
netstat -ano 查看所有的端口
netstat -ano|findstr “5900” 查看指定的端口
taskList|findstr “8696” 查看指定端口的进程
//端口
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());//端口
}
}
通信协议
协议:就是约定,就好比我们说普通话
网络通信协议:速率,传输码率,代码结构,传输控制…
TCP/IP协议簇:实际上是一组协议
TCP: 用户传输协议
UDP: 用户数据报协议
出名的协议:
TCP:
IP: 网络互连协议
TCP 和 UDP对比
TCP:相当于打电话
连接,稳定
三次握手,四次挥手
客户端,服务端
传输完成,释放连接,效率低
UDP:相当于发短信
不连接,不稳定
客户端,服务端:没有明确的界限
不管有没有连接好,都可以发
DDOS:洪水攻击
Tomcat
服务端
自定义 S
Tomcat服务器 S
客户端
自定义 C
浏览器 B
工具下载
链接:https://pan.baidu.com/s/1whuT8Gq5FGEzmxiMxX6QOA
提取码:fxxf
Tcp
客户端
//客户端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
//1 要知道服务器的地址,端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
//2 创建一个serverSocket连接
socket = new Socket(serverIP,port);
//3 发送消息 IO流
os = socket.getOutputStream();
os.write("您好,欢迎学习网络编程".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (os!=null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务器
//服务器
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1 我得有个地址
serverSocket = new ServerSocket(9999);
//2 等待客户端连接
socket = serverSocket.accept();
//3读取客户端的消息
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 {
try {
if (baos!=null)
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (is!=null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (serverSocket!=null)
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果
UDP
相当于发短信:不用连接,但是需要知道对方的地址
DatagramPacket
DatagramSocket
发送端
//不需要连接服务器
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
// 1 建立Socket
DatagramSocket socket = new DatagramSocket();
// 2 建立包
String msg = "你好,服务器";
//发送给谁
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
//数据,数据的长度,发送给谁
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
// 3发送包
socket.send(packet);
//关闭流
socket.close();
}
}
接收端
public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
//1 开放端口
DatagramSocket socket = new DatagramSocket(9090);
// 2 接收数据包
byte[] buffer = new byte[1024];
int len;
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);//接收
socket.receive(packet);//阻塞接收
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new java.lang.String(packet.getData(),0,packet.getLength()));
//3 关闭流
socket.close();
}
}
循环发送接收消息
//发送方
public class UdpSenderDemo01 {
public static void main(String[] args) throws Exception {
// 1 发送
DatagramSocket socket = new DatagramSocket(8888);
//准备数据 控制台读取System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
socket.close();
}
}
//接收方
public class UdpReceiveDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
while (true) {
//准备接收包裹 container容器
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);//阻塞式接收
//断开连接 bye
byte[] data = packet.getData();
String receiveDate = new String(data, 0, data.length);
System.out.println(receiveDate);
if (receiveDate.equals("bye")){
break;
}
}
socket.close();
}
}
多线程同时访问
public class TalkSend implements Runnable {
DatagramSocket socket = null;
BufferedReader reader = null;
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 {
socket = new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIp, this.toPort));
socket.send(packet);
if (data.equals("bye")){
break;
}
}catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int port;
private String msgFrom;
public TalkReceive(int port,String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
//准备接收包裹 container容器
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);//阻塞式接收
//断开连接 bye
byte[] data = packet.getData();
String receiveDate = new String(data, 0, data.length);
System.out.println(msgFrom +":"+receiveDate);
if (receiveDate.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(777,"localhost",9999)).start();
new Thread(new TalkReceive(8888, "老师说")).start();
}
}
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(5555, "localhost",8888)).start();
new Thread(new TalkReceive(9999, "学生")).start();
}
}
URL
统一资源定位符:定位资源,定位互联网上的某一个资源
协议:// +IP地址:端口号/项目名/资源
文件上传
服务器
public class TcpServerDemo02 {
public static void main(String[] args) throws Exception {
//1 创建服务端口
ServerSocket serverSocket = new ServerSocket(9000);
//2 监听客户端的连接
Socket socket= serverSocket.accept();//阻塞式监听,会一直等待客户端连接
// 3获取输入流
InputStream is = socket.getInputStream();
// 4 文件输出
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("接收完毕可以断开".getBytes());
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
客户端
//客户端
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
//1 创建一个Scoket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
//2 创建一个输出流
OutputStream os = socket.getOutputStream();
//3 读取文件
FileInputStream fis = new FileInputStream(new File("tonghe.jpg"));
//4 写出文件
byte[] buffer = new byte[1024];
int len;
while ((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
// 通知服务器,我已经结束了
socket.shutdownOutput();//传输完了
// 确定服务器接收完毕,才能够断开连接
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while ((len2=inputStream.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
// 5 关闭资源
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
- 点赞
- 收藏
- 关注作者
评论(0)