TCP:
客户端:
import socket
HOST = '127.0.0.1'
PORT = 3333
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
print("Connecte %s : %d OK" %(HOST, PORT))
data = s.recv(1024)
print("Receive: {}".format(data.decode()))
s.close()
服务器端:
import socket
import datetime
HOST = '0.0.0.0'
PORT = 3333
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)
while True:
conn, addr = s.accept()
print("Client %s connected!" %str(addr))
dt = datetime.datetime.now()
message = "Current time is " + str(dt)
conn.send(message.encode())
print("Send: {}".format(message))
conn.close()
UDP:
客户端:
import socket
PORT = 3333
HOST = '127.0.0.1'
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = "Hello UDP!".encode()
s.sendto(data, (HOST, PORT))
print("Send: %s to %s : %s " %(data, HOST, PORT))
s.close()
服务器端:
import socket
HOST = '0.0.0.0'
PORT = 3333
s= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, PORT))
while True:
data, addr = s.recvfrom(1024)
print("Receive %s from %s" %(data.decode(), addr))
s.close()
以上均是windows 10下使用visual studio code + python3写的小例子,希望可以对读者有一定的的启发作用!