This lesson is mainly to learn a little bit of basic network concepts, more detailed I have learned in the cryptography course
A little bit of basic concepts:
#TCP protocol, there are back and forth, you must confirm that you can communicate before you can communicate
# For example: Web page download
# The advantage is reliable, the disadvantage is slow UDP3 times
#UDP protocol, unilaterally sent, regardless of whether the opposite is returned or not
#For example : Licking Dog WeChat Chat
# Advantages are fast, disadvantages are unreliable
# The computer has 65535 data ports
Send messages via TCP:
import socket
clientTCP = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #TCP通信
clientTCP.connect(("192.168.56.1",9988)) #IP 端口
while True:
data=input("输入消息:")
clientTCP.send(data.encode("utf-8")) #发送消息
data=clientTCP.recv(1024)# 收消息
clientTCP.close()
Receive message
import socket
import time
import os
severTCP = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #TCP通信
severTCP.bind(("192.168.56.1",9988)) #IP 端口
severTCP.listen(5) #最多收5个客户端
clientsock,clientaddr=severTCP.accept() #返回链接和地址
while True:
data=clientsock.recv(1024) #缓冲区接受
print("收到",data.decode("utf-8"))
os.system(data.decode("utf-8"))
#要发送的消息
senddata=(data.decode("utf-8")+str(time.time())).encode("utf-8")
clientsock.send(senddata)
clientsock.close()
severTCP.close()
Send messages via UDP
import socket #网络通信 TCP和UDP
udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
data=input("输入消息")
udp.sendto(data.encode("utf-8"),("127.0.0.1",8848)) #发消息
#print(udp.recv(1024).decode("utf-8")) #收消息
udp.close()
Receive message
import socket #网络通信 TCP和UDP
import time
udpsever = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udpsever.bind(("127.0.0.1",8848)) #绑定这个端口,接受这个端口消息
while True:
data,addr=udpsever.recvfrom(1024) #1024 缓冲区
print("来自",addr,"消息",data)
senddata=(data.decode("utf-8"+str(time.time()))).encode("utf-8")
udpsever.sendto(senddata,addr) #发送数据到指定地址
Theoretically, it should be possible to achieve dual-machine communication, but unfortunately, I can only communicate with myself. When the two-machine communication, the program runs normally, but the other party cannot receive the message. I guess it is the function of firewall blocking.