python socket 网络编程的基本功

python socket逻辑思维整理

UDP发送步骤:

1 、先建立udp套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2、利用sendto把数据并指定对端IP和端口,本端端口可以不用指定用自动随机的
udp_socket.sendto(“发送的内容”.encode(“utf-8”), (“192.168.2.121”, 8080))
3、关闭套接字
udp_socket.clise()

UDP接收步骤:

1 、先建立udp套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2、绑定本机IP和端口
udp_socket.bind((“192.168.2.121”, 8080))
3、接收数据
recv_data = udp_socket.recvfrom(1024)
4、接收到的是两个数据分开打印出来
recv_message = recv_data[0]
recv_ip_port = recv_data[1]
print(“%s:%s” %(str(recv_ip_port), recv_message.decode(“gbk”)))
5、关闭套接字
udp_socket.clise()

TCP发送步骤:

1、建立套接字
send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2、指定服务器的IP和端口并连接服务器
send_socket.connect((“192.168.2.121”, 8081))
3、发送数据
send_socket.send(“发送内容”.encode(‘gbk’))
4、关闭套接字
send_socket.close()

TCP接收步骤

1、建立套接字
send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2、绑定IP和端口
server_socket.bind((“192.168.2.121”, 8081))
3、监听端口
server_socket.listen(128)
4、接收客户端的到来,生成两个结果值:
一个新的套接字new_client和客户端的ip+端口
new_client, address_port = server_socket.accept()
5、用新的套接字接收数据
recv_data = new_client.recv(1024).decode(‘gbk’)
6、关闭新套接字
new_client.close()
7、关闭全局套接字
send_socket.close()


具体代码案例:

UDP发送端:

import socket

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    while True:
        print("---------------input 'quit/exit'  out process!-------------")
        print("-----------------------------------------------------------")
        send_result = input("please input result: ").strip()
        if send_result == "exit":
            break
        elif send_result == "quit":
            break
        udp_socket.sendto(send_result.encode("utf-8"), ("192.168.2.121", 8080))        
    udp_socket.close()

if __name__ == "__main__":
    main()

UDP接收端:

import socket

def main():
    #创建套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    #设置ip和端口
    ip_port = ("192.168.2.121", 8080)
    #绑定商品和IP
    udp_socket.bind(ip_port)
    #接收数据
    while True:
        recv_data = udp_socket.recvfrom(1024)
        recv_message = recv_data[0]
        recv_ip_port = recv_data[1]
        #打印数据
        print("%s:%s" %(str(recv_ip_port), recv_message.decode("gbk")))
    #关闭套接字    
    udp_socket.close()
    
    
if __name__ == "__main__":
    main()

UDP发送和接收端:

import socket

def send_data(udp_socket, send_ip, send_port):
    #发送数据
    send_result = input("please input result: ").strip()     
    udp_socket.sendto(send_result.encode("gbk"), (send_ip, int(send_port)))
    
def recv_datas(udp_socket):
    #接收数据
    recv_data = udp_socket.recvfrom(1024)
    print("%s:%s===>%s" %(str(recv_data[1][0]), str(recv_data[1][1]),recv_data[0].decode('gbk')))
    
def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind(("192.168.2.121", 8082)) 
    send_ip = input('please input ip address: ').strip()
    send_port = input('please input port: ').strip()
    while True:
        print("---------------chat-------------")
        print("---1:发送---2:接收---3:退出---")
        option = input("please your select: ").strip()        
        if option == "1":
            send_data(udp_socket, send_ip, send_port)
        elif option == "2":
            recv_datas(udp_socket)
        elif option == "3":
            break
        else:
            print("you input errer!")
            continue
    udp_socket.close()   
 
if __name__ == "__main__":
    main()

TCP发送端:

import socket

def main():
    #建立套接字
    send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #指定服务器的IP和端口
    address = input('ip address: ').strip()
    ports = int(input('port: ').strip())
    #连接服务器
    send_socket.connect((address, ports))
    #发送数据
    send_data = input("input mes: ").strip()
    send_socket.send(send_data.encode('gbk'))
    #recv_data = send_socket.recv(1024)
    #print(recv_data)
    #关闭套接字
    send_socket.close()

if __name__ == "__main__":
    main()

TCP接收和发送端(带系统命令操作参数返回):

import socket,subprocess

def main():
    #建立套接字,tcp这个里面的套接字变量只用于绑定和监听
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #绑定IP和端口
    server_socket.bind(("192.168.2.121", 8081))
    #监听端口
    server_socket.listen(128)
    while True:
        print('========等待连接==========')
        #接到到客户端连接后生成一个新的套接字,并接收到客户端的ip和端口address_port
        new_client, address_port = server_socket.accept()
        #程度运行后就一直处于accept阻塞等着客户端来连接
        #有客户端连接上来了就打印出来连接的客户端ip和端口
        print('=========客户端已连接上==========')    
        print(address_port)
        #一直阻塞等客户端发数据过来
        while True:
            recv_data = new_client.recv(1024).decode('gbk')
            #print(recv_data.decode('gbk'))    
            #只要有客户端数据发来,就马上回过去,这步不阻塞                       
            if not recv_data:  # 客户在离开时没有数据过来就认为关闭了
                break
            #接收客户端发来的内容转为指令
            result = subprocess.getoutput(recv_data)
            #把指令在本地执行的内容再返还给客户端,如ipconfig,把查到的ip信息返回
            new_client.send(result.encode('gbk'))
        #关闭套接字
        new_client.close()
    server_socket.close()

if __name__ == "__main__":
    main()

tcp客户端请求文件下载

import socket

def main():
    #建立套接字
    send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #指定服务器的IP和端口
    send_socket.connect(("192.168.2.121", 8081))
    #发送要下载的数据名称    
    send_data = input("input mes: ").strip()
    send_socket.send(send_data.encode('gbk'))
    #下载文件的大小1024为1K
    recv_data = send_socket.recv(1024).decode('gbk')
    #下载发送过去的文件名文件
    if recv_data:
        with open('new' + send_data,"wb") as f:
            f.write(recv_data)
    #关闭套接字
    send_socket.close()

if __name__ == "__main__":
    main()

tcp服务端提供文件下载

import socket

def down_file_to_client(new_client, address_port):
    while True:  
        recv_file = new_client.recv(1024).decode('gbk')
        if not recv_file:  # 客户在离开时没有数据过来就认为关闭了
            break
        print("clietn %s down file is: %s " % (str(address_port), recv_file))
        files = None
        try:
            f = open(recv_file, "rb")
            files = f.read()
            f.close()
        except Exception as ret:
            print("this is %s not exsit!" % recv_file)
        if files:
            new_client.send(files)
    
def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(("192.168.2.121", 8081))
    server_socket.listen(128)
    while True:
        new_client, address_port = server_socket.accept()
        down_file_to_client(new_client, address_port)        
        new_client.close()
    server_socket.close()
    
if __name__ == "__main__":
    main()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

项目工程师余工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值