一、UDP
1.1 UDP server
云服务器开放所用端口号
114.115.128.239@udp.port == 9001
云服务器eth0(内网IP:192.168.0.61,外网IP:114.115.128.239)
root@hecs-91449:/tmp# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.0.61 netmask 255.255.255.0 broadcast 192.168.0.255
inet6 fe80::f816:3eff:fe25:7cb9 prefixlen 64 scopeid 0x20<link>
ether fa:16:3e:25:7c:b9 txqueuelen 1000 (Ethernet)
RX packets 2200793 bytes 831982428 (831.9 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 3093009 bytes 298908455 (298.9 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 789697 bytes 60933682 (60.9 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 789697 bytes 60933682 (60.9 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
root@hecs-91449:~# cd /tmp/
root@hecs-91449:/tmp# touch udptest.py
root@hecs-91449:/tmp# vim udptest.py
#脚本内容
import socket
udp_sk = socket.socket(type=socket.SOCK_DGRAM)
udp_sk.bind(('192.168.0.61',9001))
msg, addr = udp_sk.recvfrom(1024)
print(msg.decode('utf-8'))
udp_sk.sendto('hello'.encode('utf-8'),addr)
udp_sk.close()
#运行脚本
root@hecs-91449:/tmp# chmod +x udptest.py
root@hecs-91449:/tmp# python3 udptest.py
另启动一个shell,查看进程存在
root@hecs-91449:~# ps -auxw | grep udptest.py
root 547921 0.0 0.1 18572 9596 pts/2 S+ 15:27 0:00 python3 udptest.py
root 548029 0.0 0.0 9032 720 pts/3 S+ 15:28 0:00 grep --color=auto udptest.py
1.2 UDP client
import socket
ip_port = ('114.115.128.239', 9001)
udp_sk = socket.socket(type=socket.SOCK_DGRAM)
udp_sk.sendto('hello_c'.encode('utf-8'), ip_port)
back_msg, addr = udp_sk.recvfrom(1024)
print(back_msg.decode('utf-8'), addr)
udp_sk.close()
1.3 交互
二、TCP
2.1 TCP server
云服务器开放所用端口号
114.115.128.239@tcp.port == 9002
import socket
tcp_sk = socket.socket()
tcp_sk.bind(('192.168.0.61', 9002))
tcp_sk.listen()
conn, addr = tcp_sk.accept()
print(addr)
conn.send('hello_s'.encode('utf-8'))
ret = conn.recv(1024)
print(ret.decode('utf-8'))
conn.close()
tcp_sk.close()
2.2 TCP client
import socket
tcp_sk = socket.socket()
tcp_sk.connect(('114.115.128.239', 9002))
ret = tcp_sk.recv(1024)
print(ret.decode('utf-8'))
tcp_sk.send('hello_c!'.encode('utf-8'))
tcp_sk.close()
2.3 交互