socket
Socket的英文原义是“孔”或“插座”。作为 BSD UNIXI的进程通信机制,取后一种意思。通常也称作"套接字",用于描述IP地址和端口,是个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信。
Socket.本质是编程接ロ(API),对TCP/IP的封装,TCP/P也要提供可供程序员做网络开发所用的接口,这就是Socket编程接口;HTTP是轿车,提供了封装或者显示数据的具体形式; Socket是发动机,提供了网络通信的能力最重要的是, Socket,是面向客户/服务器模型而设计的,针对客户和服务器程序提供不同的 Socket系统调用套接字之间的连接过程可以分为三个步骤:服务器监听,客户端请求,连接确认。
udp
配合网络调试助手去调试
"""
@author :Eric-chen
@contact :sygcrjgx@163.com
@time :2019/12/13 14:21
@desc :
"""
from socket import *
# 1.创建套接字
udpSocket=socket(AF_INET,SOCK_DGRAM)
#2.发送地址
sendAddr=('192.168.1.108',9090)
# 3.从键盘获取数据
# sendData=raw_input("请输入要发送的数据:")
#4.发送数据到指定电脑
udpSocket.sendto(b"udp test",sendAddr)
#5.接受数据
recvData=udpSocket.recvfrom(1024)
print(recvData)
# 6.关闭套接字
udpSocket.close()
TCP
server
"""
@author :Eric-chen
@contact :sygcrjgx@163.com
@time :2019/12/16 11:47
@desc :
"""
from socket import *
import multiprocessing
# 创建tcpsocket
tcpServerSocket=socket(AF_INET,SOCK_STREAM)
# 允许服务器的socket重启后重新绑定地址
tcpServerSocket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
# 绑定地址
tcpServerAddr=('192.168.222.1',8899)
tcpServerSocket.bind(tcpServerAddr)
# 监听
tcpServerSocket.listen(5)
# 接收多个客户端连接,并且处理
while True:
# 接受客户端连接
clientSocket,clientAddr=tcpServerSocket.accept()
print("接受到的客户端:%s:%s"%(clientAddr[0],clientAddr[1]))
while True:
print(clientSocket)
# 与客户端通信
recvData=clientSocket.recv(1024)
print("from client:"+recvData.decode())
#给客户端回复信息
if len(recvData)==0:
break
clientSocket.send(recvData)
if recvData.decode()=="bye":
break
clientSocket.close()
tcpServerSocket.close()
client
"""
@author :Eric-chen
@contact :sygcrjgx@163.com
@time :2019/12/16 14:19
@desc :
"""
from socket import *
# 创建socket
tcpClientSocket=socket(AF_INET,SOCK_STREAM)
# 连接服务器
serverAddr=("192.168.222.1",8899)
tcpClientSocket.connect(serverAddr)
while True:
msg=input(">>")
print(msg)
tcpClientSocket.send(msg.encode())
recvData=tcpClientSocket.recv(1024)
print("from server%s"%recvData)
if msg=="bye":
break
tcpClientSocket.close()
We only live once, and time just goes by.

浙公网安备 33010602011771号