首页 > 编程语言 >python socket 学习

python socket 学习

时间:2023-02-02 14:03:50浏览次数:34  
标签:socket python cmd sock 学习 print data PORT

Python在网络通讯方面功能强大,今天学习一下Socket通讯的基本方式,分别是UDP通讯和TCP通讯。

UDP通讯

upd 服务端

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 import socket
5
6 ADDR,PORT = 'localhost',7878
7 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
8 sock.bind((ADDR,PORT))
9
10 print 'waiting for connection...'
11
12 while True:
13 data, addr = sock.recvfrom(1024)
14 print('Received data:', data, 'from', addr)

upd客户端

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 import socket
5
6 ADDR,PORT = 'localhost',7878
7 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
8 sock.sendto(b'hello,this is a test info !',(ADDR,PORT))

先开启server端,等待client端的接入,每请求一次client会打印如下内容

waiting for connection...
('Received data:', 'hello,this is a test info !', 'from', ('127.0.0.1', 57331))
('Received data:', 'hello,this is a test info !', 'from', ('127.0.0.1', 61396))
('Received data:', 'hello,this is a test info !', 'from', ('127.0.0.1', 61261))
('Received data:', 'hello,this is a test info !', 'from', ('127.0.0.1', 54875))

TCP通讯

TCP服务端

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 from socket import *
5 import os
6
7 ADDR,PORT = 'localhost',7878
8 sock = socket(AF_INET,SOCK_STREAM)
9 sock.bind((ADDR,PORT))
10 sock.listen(5)
11
12 while True:
13 conn,addr = sock.accept()
14 print "new conn:",addr
15 while True:
16 print 'waiting for connection'
17 data = conn.recv(1024)
18 if not data:
19 print '客户端已经断开'
20 break
21 print '执行指令',data
22 cmd_res = os.popen(data).read() #为执行传回的指令
23 if len(cmd_res) == 0:
24 print 'cmd has no output...'
25
26 conn.send(str(len(cmd_res)).encode('utf-8')) #发送大小
27 #client_chk = conn.recv(1024) 解决粘包问题 #wait client to confirm
28 conn.send(cmd_res)
29 print 'send done'
30 conn.close()
31 sock.close()

TCP客户端

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 from socket import *
4
5 ADDR,PORT = 'localhost',7878
6 sock = socket(AF_INET,SOCK_STREAM)
7 sock.connect((ADDR,PORT))
8 while True:
9 data = raw_input('>>')
10 sock.send(data)
11 print('发送信息到%s:%s' % (host, data))
12 cmd_size = sock.recv(1024)
13 print '命令结果大小 size',cmd_size
14 sock.send('准备好接收了,可以发了')
15 received_size = 0
16 received_data = b''
17 while received_size < int(cmd_size):
18 data = sock.recv(1024)
19 received_size += len(data)
20 received_data += data
21 print received_size
22 else:
23 print '=================\r\n'
24 print 'cmd receive done',received_size
25 print 'receive data:\r\n',received_data
26
27 sock.close()

 



标签:socket,python,cmd,sock,学习,print,data,PORT
From: https://blog.51cto.com/u_2820398/6033532

相关文章

  • Python调用HTTP接口并传递cookie
    #get接口调用importurllibimporturllib2get_url="http://10.10.3.63/test?id=123&name=nba"cookie_headers={"Cookie":"person_id=2468"}req=urllib2.Req......
  • python中的a,b=b,a+b怎么解释
     deffib(max):n,a,b=0,0,1whilen<max:yieldba,b=b,a+bn=n+1return'done'这里的 a,b=b,a+b......
  • python virtual environment _ example
        ......
  • Python 虚拟环境 virtualenv 笔记
    初始化virtualenv方式一:virtualenv安装virtualenv,不用sudo的话,是安装到用户home目录下pipinstallvirtualenv#此时如果virtualenv命令还不能用,需要执行......
  • 数据仓库学习
    一、数据采集&ODS1、没有时间字段的表(如:库存表),可以使用镜像采集,采集每一天的数据。2、有时间字段的表: (1)如果有修改时间字段,我们可能需要考虑他的修改时间,可以使用他的......
  • Python TensorFlow深度学习回归代码:DNNRegressor
      本文介绍基于Python语言中TensorFlow的tf.estimator接口,实现深度学习神经网络回归的具体方法。目录1写在前面2代码分解介绍2.1准备工作2.2参数配置2.3原有模型删......
  • markdown学习
    markdown标题:二级标题三级  字体hello,world!*hello,world!**hello,world! hello,world! hello,world!  引用使用引用的话加一个>就行  分割线使用......
  • 学习记录
    1.fprintf()函数概述:fprintf是C/C++中的一个格式化库函数,位于头文件中,其作用是格式化输出到一个流文件中.声明:intfprintf(FILE*stream,constchar*format,[argume......
  • 通过HH8WilEdit学习WIL 文件编码 3 资源文件实例,导出WIL.RES中的WIL,WIX文件
     unitUnit1;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls;typeTForm1=class(TFor......
  • OpenHarmony内核学习[1]--单独编译OpenHarmony标准系统内核
    内核是操作系统的核心,学习掌握OpenHarmony内核对于开发人员至关重要。笔者整理学习OpenHarmony标准系统内核笔记如下:阅读本文大约需要15分钟。(目录)OpenHarmony标准系......